Please refer to Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
You need to move the std::getline()
call into the while
statement directly:
string s;
while ( getline( readFile, s ) ) {
//operate on data...
cout << s << endl;
}
The loop will run until EOF
is reached and there is no more data to read. Whether the last line is delimited with a line break or not is irrelevant, as std::getline()
will do the right thing and return the last line's data even if it is not delimited.
So, std::getline()
actually does return the last line even if it is not delimited, but you are simply ignoring it, because this logic:
getline( readFile, s );
if ( readFile.eof() ) break;
//operate on data...
Breaks your loop prematurely if the last line is not delimited, because std::getline()
will set eofbit
on readFile
when it encounters EOF
while reading, however s
will actually contain the last line's data, which you then ignore.
By moving the std::getline()
directly into the while
statement, it will then rely on the stream's bool
conversion operator, which will return true
if eofbit
is set and none of the error flags are set (failbit
or badbit
), allowing the loop to process a non-delimited line. When the next loop iteration then tries to read past EOF
, std::getline()
will set failbit
on the stream, causing the bool
operator to return false
, breaking the loop.
