Darius Stewart
Darius Stewart

Reputation: 47

Why is my C++ code reading only one line from the input file?

Consider the following:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int score;
    char grade;
    ofstream myfileo;
    ifstream myfilei;
    myfilei.open ("example.txt");
    while (!myfilei.eof()) {
        myfilei >> score;

        cout << "Enter your score:" << endl;
        if (score >= 90)
            grade = 'A';
        else if (score >= 80)
            grade = 'B';
        else if (score >= 70)
            grade = 'C';
        else if (score >= 60)
            grade = 'D';
        else
            grade = 'F';
        cout << "Your grade was a" << grade << endl;
        switch (grade) {
            case 'A': case 'B':
                cout << "Good job" << endl;
                break;

            case 'C':
                cout << "Fair job" << endl;
                break;

            case 'F': case 'D':
                cout << "Failure" << endl;
                break;

            default:
                cout << "invalid" << endl;
        }
    }
    myfilei.close();
    myfileo.close();
    return 0;
    system ("PAUSE");
}

This code only reads the last line from an examples.txt file which is full of "scores" formatted like this:

95
21
41
78
91

Why doesn't the above code read in and output all lines?


Edited now. It's just an endless loop.

Upvotes: 1

Views: 2300

Answers (2)

Nicholas Smith
Nicholas Smith

Reputation: 11764

In your while loop you're constantly overwriting 'score', so it'll only ever be the last value in the text file. If there are multiple values that you need from the file, you're best off using an array (or similar) and adding them onto that.

Upvotes: 3

Mooing Duck
Mooing Duck

Reputation: 66971

while (!myfilei.eof()) {
    myfilei >> score;
}  

This bit of codes reads in the lines one by one and then continues when it reaches the end of the file. This is why you're only seeing it process the last line.
Any code you want to execute once per line should be inside this loop. Eg, everything up to

myfilei.close(); 

Also, since all that code is executed once per line in the file, the output doesn't need to be in a loop.

//while (!myfilei.eof()) {
    myfileo << grade << " " << score << endl;
//}  

[EDIT]
Now the infinite repetition problem is because myfilei.eof() will always return false if another error occurs first. (Like in my test case, the file fails to open.) Basic rule of thumb: never check .eof(). This is what most people do:

while (myfilei >> score) {
    //code for this score
}
//end of file or error

This attempts to read from myfilei into score, and the loop continues while it succeeds. If it fails for any reason, it breaks out of the loop.

Upvotes: 1

Related Questions