istream :: peek好奇行为wrt。紧急行动 [英] istream::peek curious behavior wrt. EOF

查看:99
本文介绍了istream :: peek好奇行为wrt。紧急行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在C ++中遇到了一个奇怪的情况。我在做类似的事情:

I've just encountered a curious situation in C++. I was doing something like:

istream in;
// ...
in.get();      // get a char (which turns out to be the last)
               // curiously ios::eof bit doesn't get set just yet

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

if(c == EOF) {
    // realize shouldn't have gotten the last char for some reason
    in.unget(): // attempt to unget, *fails* (because ios:eof bit was set)
}

现在我很好奇为什么peek设置了eof位;我觉得这很不直观。它应该只是偷看实际上没有消耗任何东西,并且不应该更改流状态。另外,为什么 unget 随后不起作用?当 good()为false或某种东西时,标准是否强制所有操作为nop?

Now I'm curious why peek sets the eof bit; I find this highly unintuitive. It's supposed to just peek not actually consume anything and shouldn't change the stream state. Also, why unget subsequently doesn't work? Does the standard mandates all operations to be nop when good() is false or something?

推荐答案


in.get();      // get a char (which turns out to be the last)
               // curiously ios::eof bit doesn't get set just yet


这不是好奇。当读取由于达到eof 而失败时,流的EOF位置1;它不是不是的意思是最后一次读取使我们到了eof。

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


现在喜欢。


此外,为什么 unget 随后不起作用?该标准是否强制所有操作在 good()为假或其他情况时为nop?

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

如果要达到<$ c $,则必须在到达EOF时自行清除流的状态。 c> unget 您在第3行检索到的那个字符。

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`
}

这篇关于istream :: peek好奇行为wrt。紧急行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆