我刚刚在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)
}
现在我很好奇为什么偷看了eof位;我发现这非常不直观。它应该只是窥视实际上不消耗任何东西,不应该改变流状态。另外,为什么unget
随后不起作用?当good()
为假或某事时,标准是否要求所有操作都是nop?
答案 0 :(得分:4)
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()
为假或某事时,标准是否要求所有操作都是nop?
......这是发生了什么。你没有以其他方式定义“不起作用”。
如果你想要在第3行检索到unget
那个角色,你必须在达到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`
}