...yes
Technically, this case only works when using
getline(). The common error is to enter the loop (because the file is still 'good'), attempt to read it, and then use whatever was read (even though the reading may have failed).
1 2 3 4 5 6
|
// BAD CODE
while (myfile.good())
{
myfile >> fooey;
foos.push_back( fooey ); // wait! what if line 4 failed?
}
| |
The example code in
blackcoder41's post above does the same thing, but since a text file has, technically, n+1 lines (where
n is the number of newlines in the file), the
getline() function
cannot fail if called when the file is
good().
Unfortunately that is the only case where that is the correct way to do it.
The proper way to do things is to always check for failure immediately after attempting input. There are two ways you can do this:
1 2 3 4
|
while (myfile >> fooey) // only continue if input is successful
{
foos.push_back( fooey );
}
| |
1 2 3 4 5 6 7
|
while (true)
{
myfile >> fooey; // try to get input
if (!myfile) break; // only continue if input was successful
foos.push_back( fooey );
}
| |
After the loop ends you can check to see if termination was due to
eof() or some other
fail()ure.
The method you choose depends on what you are doing, and how you enter the loop. Here is an example:
http://www.cplusplus.com/forum/beginner/18258/#msg92955
Variations abound.
Hope this helps.