c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?

标签 c++ iostream c++-faq

我刚刚在 this 中找到一条评论回答说在循环条件中使用 iostream::eof “几乎肯定是错误的”。我通常使用类似 while(cin>>n) 的东西——我猜它会隐式检查 EOF。

为什么使用 while (!cin.eof()) 显式检查 eof 是错误的?

它与在 C 语言中使用 scanf("...",...)!=EOF 有何不同(我经常毫无问题地使用它)?

最佳答案

因为 iostream::eof 只会返回 true after 读取流的末尾。它表示下一次读取将是流的末尾。

考虑这个(并假设下一次读取将在流的末尾):

while(!inStream.eof()){
  int data;
  // yay, not end of stream yet, now read ...
  inStream >> data;
  // oh crap, now we read the end and *only* now the eof bit will be set (as well as the fail bit)
  // do stuff with (now uninitialized) data
}

反对:

int data;
while(inStream >> data){
  // when we land here, we can be sure that the read was successful.
  // if it wasn't, the returned stream from operator>> would be converted to false
  // and the loop wouldn't even be entered
  // do stuff with correctly initialized data (hopefully)
}

关于你的第二个问题:因为

if(scanf("...",...)!=EOF)

相同
if(!(inStream >> data).eof())

一样

if(!inStream.eof())
    inFile >> data

关于c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770089/

相关文章:

c++ - 取消对象创建的简洁方法

c++ - 如何清除cin读取的内容

c++ - 有哪些 C++ 智能指针实现可用?

c++ - 为什么 std::atomic_is_lock_free 不是静态 constexpr?

c++ - QTableView 列宽

c++ - 如何读取输入流缓冲区中存储的字符数

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 什么是 undefined reference / Unresolved external symbol 错误,我该如何解决?

c++公共(public)对象更改应该调用函数

c++ - 什么决定从 std::endl 输出哪些字节