Recently I’ve come across a bug in my software that was caused by a stringstream object that had it’s EOF flag set before I expected it. Even though I managed to found out what happened, I was not able to find out why this is happening. An example:
stringstream test ("a b");
char temp, temp2;
test >> temp >> temp2;
cout << "eof: " << test.eof() << endl;
When run, this shows:
eof: 0
This is the output I would expect. (I would expect the stringstream to set the EOF flag to 1 when i attempt to read something again)
However, when I make a small change to the above example:
stringstream test ("4 2");
int temp, temp2;
test >> temp >> temp2;
cout << "eof: " << test.eof() << endl;
the output shows:
eof: 1
Why does the EOF flag get set in this situation, but not in the previous one?
operator>>skips whitespace characters by default, so the first read into a char will reada, the second will skipand readb, a third would reach the end of the string and fail, setting the eof flag.In the
intcase, multiple characters can be read while parsing anintbecause anintmay be represent by multiple digits. While reading the integer a second read attempt will be made after reading the2. This will set the eof flag for the stream although the read of theintwill succeed.This is why you should check
!fail()and notgood()to see if a read operation succeeded and why the conversion of a stream tobool(orvoid*in C++03) also uses!fail().