@GRex2595 no,
while(!file.eof())
does
not repeat until you hit the end of the file, it repeats until the internal EOF flag belonging to the
file ifstream has been set.
This can mean one of several things
1) You get lucky (or unlucky) and everything "appears to work", that the EOF flag is set upon reading the last line of valid data of the file with getline
2) Your loop overflows by-one because getline ends up causing the EOF flag to be set after reading past the end of the last line of valid data (e.g. if you have an extra newline at the end of the file)
3) You get stuck in an infinite loop because something causes the stream to be set to an invalid state part way through reading the file (or maybe it's invalid before you even started?) - this one can easily happen if you read data using the
>>
operator instead of getline.
What you need to do to read until the end of a file (or until it fails) is put the call to getline as part of the while condition
1 2 3 4 5
|
std::ifstream file( "myfile.txt" );
std::string str;
while( std::getline( file, str ) )
{
}
|
This is a far more reliable method. The eof flag is more useful after you've finished reading data, e.g. in case you need to determine if the stream is still in a good state (if EOF flag is set, then you know it didn't fail partway through due to some error, or due to the file not being opened, etc). Checking it before trying to read data generally isn't helpful
Alternatively, if you're using
>>
to read from the stream (e.g. if you have a file which you expect to contain only numeric data):
1 2 3 4 5
|
std::ifstream file( "myfile.txt" );
int n;
while( file >> n )
{
}
|