Stream state in loop conditions

D

Duck Dodgers

This was originally posted in comp.std.c++, and never received any
replies, so I'll be rude and cross-post it here because I really am
interested in the answer. ;)

I see this idiom a LOT for reading until end-of-file:

while ( cin >> var ) { /* ... */ }
while ( getline ( cin, s ) ) { /* ... */ }

Is this guaranteed to work? The standard makes no mention of operator
void* looking at eofbit at any point. The way I'm reading the standard,
it looks like if no characters are read then failbit is set, which
operator void* uses. The idiom would work under that interpretation
because if eofbit is set then no characters are read and failbit is set
shortly thereafter, causing the loop to terminate because operator
void* relies on fail().

There's also a clause about sentry that suggests both failbit and
eofbit are set if end-of-file is reached (section 27.6.1.1.2), but I'm
not quite sure that's applicable to my question.

Thanks for your time.
 
R

Ron Natalie

Duck said:
There's also a clause about sentry that suggests both failbit and
eofbit are set if end-of-file is reached (section 27.6.1.1.2), but I'm
not quite sure that's applicable to my question.

Thanks for your time.

There are technically two errors. eofbit occurs when the end of the
input data occurs, in addition the failbit occurs because your input
operation >> fails to get what was expected by it.
 
R

Ron Natalie

Duck said:
There's also a clause about sentry that suggests both failbit and
eofbit are set if end-of-file is reached (section 27.6.1.1.2), but I'm
not quite sure that's applicable to my question.

Thanks for your time.

eofbit and failbit are set in your example (probably, I need to see
what the full type definitions of your variables are). However,
they don't necessarily come on together universally. Obviously
you can fail without being at the end of file when the data in the
stream is not what is expected by the input operation. Furhter
some input operations (like reading strings or unformatted reads)
can encounter the end of file without failing the input operation.
 
D

Duck Dodgers

The example is assuming that var is declared as int and s is declared
as std::string. stdin would be from an interactive terminal, and the
end-of-file key sequence is entered without any other input. The idea
is that, all else being correct, if end-of-file is reached, will
failbit get set along with eofbit so that the loop terminates?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top