istream::偷看奇怪的行为.EOF

istream::peek curious behavior wrt. EOF

本文关键字:EOF istream      更新时间:2023-10-16

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

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?

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

这不是"好奇"。当读取由于达到EOF而失败时,流的EOF位被设置;它并不意味着"最后一次阅读把我们带到了eof"。

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

就像现在一样。

此外,为什么unget随后不起作用?当good()为false或其他什么时,标准是否要求所有操作都为nop?

这就是正在发生的事情。您未能以其他方式定义"不起作用"。

如果要unget在第3行检索到的字符,则必须在达到EOF时自己清除流的状态。

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