我刚刚发现一条评论this回答说使用iostream::eof
在循环条件中“几乎肯定是错误的”。我通常使用类似的东西while(cin>>n)
- 我猜它隐式检查 EOF。
为什么显式使用检查 eofwhile (!cin.eof())
错误的?
与使用有何不同scanf("...",...)!=EOF
在C中(我经常使用它没有问题)?
Because iostream::eof
只会返回true
after读取流的末尾。确实如此not指示下一次读取将是流的末尾。
考虑这一点(并假设下一次读取将在流的末尾):
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())
and not与
if(!inStream.eof())
inFile >> data
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)