If Loops & Input From Data File

Hello all! I'm a beginner C++ student in her first class. I seem to be struggling with getting the code to read the file inside my folder. This is the code I have - however, one of my major errors is the code does not find the file name. I have both the "IfLoopsandInputFromDataFile" file and "TestScore.txt" file within the same file folder on my desktop, but it's not working. Any guidance is appreciated! Thanks in advance.

My instructions are:
Write a C++ program that computes a student’s grade for an assignment as a percentage given the student’s score and total points. The final score must be rounded up to the nearest whole value. 2. Add the variables & math computations necessary to complete the calculations. Make sure you use the ceil function in the <cmath> header file.
- The input to the program must come from an external data file that you create. You will create a text file. The file will contain a single line with the score and total separated by a space.
- Display the floating-point result up to 5 decimal places. Output the results to the screen. The output must be labeled clearly and formatted neatly.
- In addition, you must print to the console “Excellent” if the grade is greater than or equal to 90, “Well Done” if the grade is less than 90 and greater than or equal to 80, “Good” if the grade is less than 80 and greater than or equal to 70, “Need Improvement” if the grade is less than 70 and greater than or equal to 60, and “Fail” if the grade is less than 60.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 //include header files
#include
#include //for ceil function
#include //Header file for file opening
#include //for set precession function
using namespace std; 
//starting point of program execution
int main()
{
    //float type of data variables
    float studentScore; 
    float totalPoints; 
    float percentageOfGrade; 
    float finalScore; 
    ifstream inFile;
    inFile.open("TestScores");
    inFile>>studentScore>>totalPoints;

    finalScore=ceil(studentScore);
    /*Calculate percentage of student grade marks by dividing the final score by total score and multiply bt 100 */
    percentageOfGrade=(finalScore/totalPoints)*100;
    cout<<"Student Score : " <
    cout<<"Total points: " <
    /* print percenate to 5 decimal places using setprecision(5). */
    cout<"Percentage of FInal Score with 5-decimal places " <
    
    if (percentageOfGrade>90)
    cout<<"Excellent"<
 
    else if (percentageOfGrade>80)
    cout<<"Well Done"<
  
    else if(percentageOfGrade>70) 
    cout<<"Good"<

    else if (percentageOfGrade>=60)
    cout<<"Need Improvement"<

    else cout<<"Fail"<

    inFile.close();

    return 0; 
} //end of main method 
First please show your input file contents.

Second you should always check that the file opened correctly. Something like:
1
2
3
4
5
if(!inFile)
{
   std::cerr << "Failed to open input file.\n";
   return 1;
}


Third the file name you're trying to use doesn't seem to match the actual file name.

Do you realize that unless you use an "absolute" ("C:\temp\somefilename.txt") file name the file must reside in the current working directory? The working directory varies depending on how you invoke the program and several other factors. So you need to show how you're actually trying to run the program.


It will look for the file in the "current working directory" of the process. This is not necessarily the same as the directory where your executable file is located.

How do you execute the program?
- You use the file browser and double click on the executable file? Then the working directory will usually be set to the same directory where the executable file is located.
- You use a terminal window (called the Command Prompt on Windows)? In that case the working directory will be the directory that you have navigated to using the cd command.
- You hit the run button inside your IDE? Then the working directory will usually be the same as the "project folder".

Update: And make sure you spell the file name correctly. You mentioned "TestScore.txt" but your program seems to try and read from a file named "TestScores".
Last edited on
L2-5 #include should be followed by the name of a header file (enclosed within <> for standard header files.

It's also good practice to define a variable as near as possible to where it is first used and to initialise it when defined.

There's also issues with the cout statements with what seems to be missing parts from the right of the statements??

Perhaps something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>

int main() {
    std::ifstream inFile("TestScore.txt");

    if (!inFile)
        return (std::cout << "Cannot open file\n"), 1;

    double studentScore {};
    double totalPoints {};

    inFile >> studentScore >> totalPoints;

    const auto finalScore {std::ceil(studentScore)};
    const auto percentageOfGrade {finalScore / totalPoints * 100};

    std::cout << "Student Score : " << finalScore << '\n';
    std::cout << "Total points: " << totalPoints << '\n';
    std::cout << "Percentage of Final Score with 5-decimal places " << std::setprecision(5) << percentageOfGrade << '\n';

    if (percentageOfGrade > 90)
        std::cout << "Excellent\n";
    else if (percentageOfGrade > 80)
        std::cout << "Well Done\n";
    else if (percentageOfGrade > 70)
        std::cout << "Good\n";
    else if (percentageOfGrade >= 60)
        std::cout << "Needs Improvement\n";
    else std::cout << "Fail\n";
}

Thanks for the responses!!

I have updated the file name to just TestScore.txt

It's contents are:

88.7 90

which I believe is all that needs to be in there. I'm not 100% sure.

I'm still not understanding how to have my code read the TestScore.txt file. The only way I read my program for the class is a) Right - clicking in Visual Studio Code and clicking "Run" & b) by opening the Terminal directly from the folder in which it is saved (This sounds weird, but it shows the program running this way).
If you open a cmnd prompt and issue a dir command, what is the name of the directory displayed? Can you see the name of your program (with .exe at the end)? Can you see TestScore.txt file?

If not, in what directory is your compiled program located? What directory is TestScore.txt located (use Windows search). If these are in the same directory, then use CD to change the current directory to that one. Now execute the program which should work OK.

If these are not in the same directory, then you have 2 choices. 1) Copy/move TestScore.txt to the directory in which your .exe program is located. Executing the program should now work. 2) In the code specify the full complete file name instead of just "TestScore.txt". Then re-compile and try executing the program again.
The only way I read my program for the class is a) Right - clicking in Visual Studio Code and clicking "Run" & b) by opening the Terminal directly from the folder in which it is saved (This sounds weird, but it shows the program running this way).

I cannot stress enough how useful the console is. if you can spend 2 days learning dos and unix command lines well enough to get some stuff done, it may help your efficiency a ton.
dos:
to get to it, window key and type cmd
cd path\path2 //change directory cd \ to root
dir //list contents
programname //rune programname.exe (or a few other extensions, bat, scr, com, etc-- all programs)
del filename //delete a file
and then it gets fun:
programname > out.txt //run your program and dump its output to a text file
programname >> out.txt //run your program and APPEND to existing file
programname << in.txt //run your program and read from a text file as if typed at keyboard, very fast to debug boring menu driven schoolwork programs

that alone will get you a long, long way.
unix works very similar but uses different letters. ls is dir. / is \ on pathing. you have to type junk to run a program: ./programname.extensionifany. rm is del. to and from text files is same.

visual studio's run is confusing about the folder paths if you didn't know to change it in the project settings. its annoying about closing the console after running. You can do everything from it, but ... give the console a try, see if you think it makes life easier.
temporarily add this to the beginning of main()
system("echo %CD%");
When you run the program it will print the name of the directory where it runs.

Topic archived. No new replies allowed.