istream::peek curious behavior wrt. EOF

試著忘記壹切 提交于 2019-12-06 06:18:27
in.get();      // get a char (which turns out to be the last)
               // curiously ios::eof bit doesn't get set just yet

This is not "curious". The stream's EOF bit gets set when a read fails due to having reached eof; it does not mean "the last read took us to eof".

c = in.peek(); // attempt to peek, return EOF and now set ios::eof bit

Like now.

Also, why unget subsequently doesn't work? Does the standard mandates all operations to be nop when good() is false or something?

... which is what's happening. You failed to otherwise define "doesn't work".

You'll have to clear the stream's state yourself when EOF was reached, if you want to unget that character you retrieved on line 3.

istream in;
// ...
in.get();      // assume this succeeds (*)

c = in.peek(); // assume this fails and sets EOF bit

if (!in) {
   in.clear(); // clear stream error state for use
   in.unget(); // "put back" that character (*)
}
else {
   // next char from .get() will be equal to `c`
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!