filipe wrote: |
---|
When used as a boolean value, the expression fin >> str will evaluate to false if the stream goes into fail(), bad() or eof() states. |
wolfgang wrote: |
---|
The difference here is that fin >> str will read up to a whitespace and stop and in a loop that reads every word in. The reason it works like !entrance.eof() is because entrance.eof() checks to see if the badbit or eof flag is set |
I though so too, until a week ago or so, when this post surfaced:
http://www.cplusplus.com/forum/general/34292/
It appears that the results from
operator! and
operator void* depend only on the value of the failbit and badbit, but not on the value of eof. The expression
fin >> str
is therefore not strictly stronger condition compared to the expression
!entrance.eof()
. Now I see, that the idiom
while (fin >> str) { ... }
actually works not because the condition fails immediately when the end of the stream is reached (; if that was the case the last word would escape from the body of the loop), but because the condition fails when the stream was exhausted and
fin has no more characters to pass to
str, which results in a
failbit.
Thinking further in this direction, using the
while (!fin.eof()) { fin >> str; ... }
approach may be generally incorrect. It may work for extracting strings, but it could be incorrect for say,
char-s. According to some sources (see **), the
eof bit is set when you try to read something past the end of the file, not when you read the last character before the end of the file. So, if the previous extraction reached the end of the file, without reading past it, the
!fin.eof()
condition will still evaluate to
true, but the following extraction in the next loop iteration will be unsuccessful, because there is nothing left to read, and there will be erroneous extra processing of non-extent input. I'm not sure on this. Any confirmation?
** Random picks:
http://cpp.comsci.us/etymology/include/iostream/eof.html
http://stackoverflow.com/questions/292740/c-reading-from-a-file-blocks-any-further-writing-why