istream::偷看奇怪的行为.EOF
istream::peek curious behavior wrt. EOF
我刚刚在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`
}
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 为什么istream不支持右值提取
- 将无符号char*转换为std::istream*C++
- 需要从 istream 和 ostream 派生 iostream
- 使用std::istream::peek()总是安全的吗
- 使用 istream 参数读取的 istream 函数
- istream std::cin如何修改自定义istream缓冲区
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 读取 c++ istream 直到 EOF,同时丢弃内容
- 如何使用 istream::ignore() 函数时检查 EOF 条件
- GCC 4.7 istream::tellg() 在达到 EOF 后返回 -1
- C++istream EOF不能保证故障位
- C++的 istream::eof() 的不一致是规范中的错误还是实现中的错误?
- C++ eof 上的 istream tellg()/fail() :行为改变;解决方法
- istream::偷看奇怪的行为.EOF
- 还有什么比使用istream eof更好的方法来读取文件直到它结束呢?
- ostream << istream 并在空文件上测试 EOF,从 istream 获取字符的替代方法
- Std::istream不会抛出eof异常(已启用)
- 捕获istream忽略的(eof-)异常
- C++:std::istream 检查 EOF 而不读取/使用令牌/使用运算符>>