gpt4 book ai didi

c++ - istream::peek 奇怪的行为。结束符

转载 作者:搜寻专家 更新时间:2023-10-31 01:16:48 24 4
gpt4 key购买 nike

我刚刚在 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

就像现在一样。

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

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

如果您想取消您在第 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`
}

关于c++ - istream::peek 奇怪的行为。结束符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8763720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com