Need help stopping a while loop

Oct 29, 2015 at 1:05am
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)

Oct 29, 2015 at 2:18am
while(!myFile.eof())
Oct 29, 2015 at 2:45am
show some code :P
Oct 29, 2015 at 9:37am
1
2
3
4
while(fread(&file,sizeof(file),1,filename))
{
    cout<<file;
}


try this!
Oct 29, 2015 at 10:59am
@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 Oct 29, 2015 at 11:03am
Topic archived. No new replies allowed.