Reputation: 1221
I'm a beginner in programming and I need help with this snippet of code presented in my book.
for (My_type var; ist >> var;) { // read until end of file
// maybe check that var is valid
// do something with var
}
if (ist.fail()) {
ist.clear();
char ch;
// the error function is created into the book :
if (!(ist >> ch && ch == '|')) error("Bad termination of input\n");
}
// carry on : we found end of file or terminator
This example is about reading values from a file. I've tried to use this but I'm having some troubles in understanding how it works :
If I try to test the stream state after the loop I get both eof
and fail
state, how is that possibile ? How to avoid triggering both fail
and eof
?
When is EOF triggered exactly ? From my test it seems to be triggered when I reach the last value of a sequence, is this definition correct ?
Thank you.
Upvotes: 0
Views: 58
Reputation: 48928
If I try to test the stream state after the loop I get both eof and fail state, how is that possibile ? How to avoid triggering both fail and eof ?
It is possible if there is a character that cannot be converted to My_type
, and that character is the last character in the file. Then, failbit
and eofbit
will be set.
When is EOF triggered exactly ? From my test it seems to be triggered when I reach the last value of a sequence, is this definition correct ?
Yes, eofbit
gets set when the last character is read.
Quoting from std::basic_istream
:
The extraction stops if one of the following conditions are met:
end-of-file occurs on the input sequence;
inserting in the output sequence fails (in which case the character to be inserted is not extracted);
an exception occurs (in which case the exception is caught, and only rethrown if failbit is enabled in exceptions()).
Upvotes: 4