Need help stopping a while loop

So I am reading in a file with a while loop. at the end of the file it reads END. My while loop prints it and for the love of god I can not figure out how to condition the while loop so it stops at that point.

while(myFile)

while(!myFile.eof())
show some code :P
1
2
3
4
while(fread(&file,sizeof(file),1,filename))
{
    cout<<file;
}


try this!
@Ericool
Don't loop on EOF! The flag isn't set until you try to read something and fail, which means that you have an extra iteration of the loop with invalid data. Prefer looping on your input statement, instead.

@OP
If you mean that you actually finish on 'END', and you just want to escape the while loop, use a break statement, or put it as part of the condition.

Here's an example putting both of that together:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string val;
while (myFile >> val) { // or std::getline
    if (val == "END")
        break;

    // do stuff here with val
}

// or

while ((myFile >> val) && val != "END") {
    // do stuff here with val
}

// val == END, myFile reached EOF, or the read failed in some other way by here. 
Last edited on
Topic archived. No new replies allowed.