0

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 :

  1. 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 ?

  2. 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.

1 Answer 1

4

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()).

Sign up to request clarification or add additional context in comments.

3 Comments

I think I'm understanding this loop better now, but I still have a problem that needs to be clarified, if both eof and fail get triggered after the loop, then the test for fail will be true everytime. Now suppose I want to read 10 integers from a file and accept only eof as terminator, I will read using the for loop and at the end I will have both eof and fail up. At this point what can I do ? I can't throw an exception using error if the read fails because it will happen for sure as I understand. I'm not really understanding the book example.
@Piero What you could do is first check for eof, then check fail. This way, you notice when the file ended, but don't care if the last character was valid or not.
So I think I should probably assume that the author of the book wrote a wrong example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.