为什么iostream :: eof在循环条件内被认为是错误的? [英] Why is iostream::eof inside a loop condition considered wrong?
问题描述
我刚刚在这个回答说,在循环条件中使用 iostream :: eof
是几乎肯定错误。我通常使用类似 while(cin>> n)
- 我猜是隐式检查EOF,为什么使用 iostream显式检查eof: :eof
错了?
与使用 scanf(...,...)!= EOF
因为 iostream :: eof $ c $ c>只会在读取流的结尾之后返回
true
。
请考虑这一点(并假设下一次读取将是在流中)。
while(!inStream.eof()){
int data;
// yay,not end of stream yet,now read ...
inStream>>数据;
// oh crap,现在我们读取结束和*只有*现在eof位将被设置(以及失败位)
//使用(现在未初始化的)数据进行操作
}
对此:
int data;
while(inStream>> data){
//当我们到这里时,我们可以确保读取成功。
//如果不是,来自运算符的返回流>>将被转换为false
//并且甚至不会进入循环
//使用正确初始化的数据进行填充(希望)
}
第二个问题:因为
if(scanf(...,...)!= EOF)
if(!(inStream>> data).eof())
if(!inStream.eof())
inFile>>数据
I just found a comment in this answer saying that using
iostream::eof
in a loop condition is "almost certainly wrong". I generally use something likewhile(cin>>n)
- which I guess implicitly checks for EOF, why is checking for eof explicitly usingiostream::eof
wrong?How is it different from using
scanf("...",...)!=EOF
in C (which I often use with no problems)?解决方案Because
iostream::eof
will only returntrue
after reading the end of the stream. It does not indicate, that the next read will be the end of the stream.Consider this (and assume then next read will be at the end of the stream):
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 }
Against this:
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) }
And on your second question: Because
if(scanf("...",...)!=EOF)
is the same as
if(!(inStream >> data).eof())
and not the same as
if(!inStream.eof()) inFile >> data
这篇关于为什么iostream :: eof在循环条件内被认为是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!