使用 getline() 函数逐行读取文件中的段落,并使用 while 循环和代码 fin.eof() 但结果是无限循环

Reading paragraph in file line by line using getline() function and using while loop with codition fin.eof() but result is infinte loop

ben_stokes.txt

The great Irish sports writer Con Houlihan used to say that every team should have a redhead.

And it's true that Ben Stokes' combative nature, allied to his powerful frame and outrageous talent,

lifted England to another level. Never was that more true than when he secured his place in English

cricket history with an indefatigable batting display in the 2019 World Cup final.

代码-1

#include<iostream>
#include<fstream>
int main()
{
    std::ifstream fin;
    char str[40];
    int i=1;
    
    fin.open("ben_stokes.txt", std::ios::in);
    
    while(!fin.eof())
    {
        fin.getline(str,39,'\n');
        fin.clear();
        
        std::cout<<str;
            
    }
    fin.close();
}

输出:

The great Irish sports writer Con Houlihan used to say that every team should have a redhead.And it's true that Ben Stokes' combative nature, allied to his powerful frame and outrageous talent,lifted England to another level. Never was that more true than when he secured his place in Englishcricket history with an indefatigable batting display in the 2019 World Cup final._

只是光标闪烁程序永远不会结束。所以我在代码中添加了额外的字符 ! 来检查发生了什么。

Code-2

#include<iostream>
#include<fstream>
int main()
{
    std::ifstream fin;
    char str[40];
    int i=1;
    
    fin.open("ben_stokes.txt", std::ios::in);
    
    while(!fin.eof())
    {
        fin.getline(str,39,'\n');
        fin.clear();
        
        std::cout<<str<<'!';
            
    }
    fin.close();
}

输出

The great Irish sports writer Con Houl!ihan used to say that every team shoul!d have a redhead.!And it's true that Ben Stokes' combati!ve nature, allied to his powerful fram!e and outrageous talent,!lifted England to another level. Never! was that more true than when he secur!ed his place in English!cricket history with an indefatigable !batting display in the 2019 World Cup!final.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... (upto infinite).

我查看了与此相关的Whosebug上的其他问题。我知道这是由于 fin.eof() 造成的。它现在只检查 EOF 是否发生,它不检查下一次读取是否 EOF ?所以我们进入循环并读取 EOF 所以 eof-bit 和 fail-bit 设置正确吗?那么为什么它不会在下一次迭代中作为 eof 位集退出循环。

调用 clear 将重置 eof 标志,因此 while 循环的条件将始终计算为 true。在 getline 之前调用 clear 代码将起作用。