从文件中读取时程序不会终止

Program does not terminate when reading from a file

本文关键字:终止 程序 文件 读取      更新时间:2023-10-16

看到代码中的大量文件操作,我有点尴尬。但好的旧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()作为文件读取循环的退出条件。尝试

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

如果你解释next实际上应该做什么,我可以试着告诉你如何做,尽管我个人通常读取不需要任何控制整数的getlineoperator>>文件。

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

所以把它改成这样:

string word;
while(!file.eof()) {
  file >> word;
  cout << next;
  next++;
}