Intelwalk
Intelwalk

Reputation: 671

C++ Reading From File Loop Messing Up

I have a problem with a simple file read. I have 4 four long lines of T/F's with a count at the beginning. I read in with a myfile >> count, and myfile >> value to get the values with a while with the count to finish it off the line and goto the next but I have a problem going to the third line for some reason. Not sure how to get the data file on here... Thanks for looking!

int main() {
    ifstream myfile;
    int count;
    string value;

    myfile.open("branches.txt");

    while(!myfile.eof()) {
        myfile >> count;
        cout << count << endl;

        while(count > 0) {
            myfile >> value;
            count--;
            //cout << value;
        }

        myfile >> count;
    }

    system("pause");
    return 0;
}

Upvotes: 0

Views: 161

Answers (2)

Karl Knechtel
Karl Knechtel

Reputation: 61478

You appear to be attempting to read the count twice per line: at the beginning and end of the while loop.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206508

Do not use feof() it just tells you what the result of the previous read was. The correct way to read a file is

while( read( file, buffer ) ) 
{    
    //do something 
} 

Upvotes: 4

Related Questions