Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to test if a std::istream has reached the end without reading from it.

I know that I can check for EOF like this:

if (is >> something) 

but this has a series of problems. Imagine there are many, possibly virtual, methods/functions which expect std::istream& passed as an argument. This would mean I have to do the "housework" of checking for EOF in each of them, possibly with different type of something variable, or create some weird wrapper which would handle the scenario of calling the input methods.

All I need to do is:

if (!IsEof(is)) Input(is);

the method IsEof should guarantee that the stream is not changed for reading, so that the above line is equivalent to:

Input(is)

as regards the data read in the Input method.

If there is no generic solution which would word for and std::istream, is there any way to do this for std::ifstream or cin?

EDIT: In other words, the following assert should always pass:

while (!IsEof(is)) {
  int something;
  assert(is >> something);
}
like image 975
eold Avatar asked Apr 24 '11 13:04

eold


1 Answers

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

like image 154
Ephphatha Avatar answered Sep 17 '22 23:09

Ephphatha