C++: std::istream check for EOF without reading / consuming tokens / using operator>>

The istream class has an eof bit that can be checked by using the is.eof() member.

Edit: So you want to see if the next character is the EOF marker without removing it from the stream? if (is.peek() == EOF) is probably what you want then. See the documentation for istream::peek


That's impossible. How is the IsEof function supposed to know that the next item you intend to read is an int?

Should the following also not trigger any asserts?

 while(!IsEof(in))
 {
    int x;
    double y;
    if( rand() % 2 == 0 )
    {
       assert(in >> x);
    } else {
       assert(in >> y);
    }
 }

That said, you can use the exceptions method to keep the "house-keeping' in one place.

Instead of

   if(IsEof(is)) Input(is)

try

   is.exceptions( ifstream::eofbit /* | ifstream::failbit etc. if you like */ )
   try {
     Input(is);
   } catch(const ifstream::failure& ) {
   }

It doesn't stop you from reading before it's "too late", but it does obviate the need to have if(is >> x) if(is >> y) etc. in all the functions.