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

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

提问人:Abhishek Mane 提问时间:8/15/2021 更新时间:8/16/2021 访问量:105

问:

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._

只是光标闪烁程序永无止境。因此,我只在代码中添加了额外的字符来检查发生了什么。!

代码-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).

我检查了与此相关的 stackoverflow 上的其他问题。我知道这是由于.它只是检查现在是否发生,它不检查下一次读取是否发生?因此,我们进入循环并读取 EOF-BIT 和 FAIL-BIT 设置对吗?那么为什么它没有在下一次迭代时作为 eof-bit set 退出循环。fin.eof()EOFEOFEOF

C++ IFstream EOF GetLine

评论

1赞 ShahzadIftikhar 8/15/2021
无关:喜欢你的文件名ben_stokes.txt
0赞 Ghasem Ramezani 8/15/2021
您可以使用单个语句读取整个文件:github.com/another-ghasem/examples/blob/master/sub_examples/...for
2赞 chris 8/15/2021
你确定它甚至正在打开文件吗?没有错误检查,也不会检查其他标志。Смотритетакже: stackoverflow.com/questions/5605125/...eof()
0赞 Evg 8/16/2021
我建议你逐行仔细分析你的程序,检查哪些标志被设置,哪些标志被检查。
0赞 Abhishek Mane 8/18/2021
@ShahzadIftikhar嘿,我们来自邻国,我们应该在 WhatsApp 上联系吗?

答:

2赞 Yun 8/15/2021 #1

调用将重置标志,因此 -loop 的条件将始终计算为 。调用之前,代码将起作用。cleareofwhiletruecleargetline