【发布时间】:2014-10-22 18:57:01
【问题描述】:
看到代码中的大量文件操作,我有点畏缩。但是好老的freopen() 在这个特定的代码段中让我失望了-
int main()
{
ifstream fin;
int next=0;
fin.open("In.txt");
if(fin.is_open())
{
while(!fin.eof())
{
cout<<next;
next++;
}
}
else cout<<"Unable to open file"<<endl;
return 0;
}
我包含的头文件是 iostream、fstream 和 cstdio。这进入了一个无限循环。
我的问题是,我作为输入提供的文件肯定已经结束了。但是为什么程序没有终止呢?提前致谢。
【问题讨论】:
-
你没有从文件中读取,这意味着你没有到达文件的末尾。
-
当然,如果不阅读任何内容,您永远不会到达 EOF。无论如何,您不应该使用
eof()作为终止条件。在假设它们成功之前检查输入操作是否成功。 -
while(!fin.eof())相关:Why is iostream::eof inside a loop condition considered wrong?