【问题标题】:Program does not terminate when reading from a file [duplicate]从文件读取时程序不会终止[重复]
【发布时间】: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() 作为终止条件。在假设它们成功之前检查输入操作是否成功。

标签: c++ file eof


【解决方案1】:

您几乎不应该使用eof() 作为文件读取循环的退出条件。试试

std::string line;
if(fin.is_open())
{
    while(getline(fin, line))
    {
        cout<<line;
    }
}

如果您解释 next 实际应该做什么,我可以尝试告诉您如何做,尽管我个人通常使用不需要任何控制整数的 getlineoperator&gt;&gt; 读取文件。

【讨论】:

    【解决方案2】:

    您正在打开一个文件,但实际上并没有从中读取。每次检查是否已到达文件末尾时,流都在同一位置。

    所以把它改成这样:

    string word;
    while(!file.eof()) {
      file >> word;
      cout << next;
      next++;
    }
    
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2017-04-17
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多