Search code examples
c++visual-c++streamcharistringstream

Why istringstream appends '-1' character at the end of stream?


I've noticed that when I'm using istringstream eof() doesn't return true even if the whole string is "consumed". For example:

char ch;
istringstream ss{ "0" };
ss >> ch;
cout << ss.peek() << " " << (ss.eof() ? "true" : "false");

Outputs(VS2015):

-1 false

Solution

  • eof() isn't supposed to return true when all the data is consumed. It's supposed to return true when you attempt to read more data than is available.

    In this example, you never do that.

    In particular, peek is a "request", that won't set EOF even when there's nothing left to read; because you're, well, peeking. However, it will return the value of the macro EOF (commonly -1), which is what you're seeing when you output peek()'s result. Nothing is "appended" to the stream.

    Read the documentation for functions that you use.