首页 > 解决方案 > 使用 getline() 函数逐行读取文件中的段落并使用带有编码 fin.eof() 的 while 循环,但结果是无限循环

问题描述

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 的其他问题。我知道这是由于fin.eof(). 它只是检查现在EOF是否发生它不检查下一次读取是否EOF发生?所以我们进入循环并读取EOFeof-bit 和 fail-bit 设置正确吗?那么为什么它不会在下一次迭代中作为 eof 位集退出循环。

标签: c++ifstreameofgetline

解决方案


调用clear将重置eof标志,因此while-loop 的条件将始终评估为trueclear 之前 调用getline,代码将起作用。


推荐阅读