提问人:Abhishek Mane 提问时间:8/15/2021 更新时间:8/16/2021 访问量:105
使用 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
问:
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()
EOF
EOF
EOF
答:
2赞
Yun
8/15/2021
#1
调用将重置标志,因此 -loop 的条件将始终计算为 。调用之前,代码将起作用。clear
eof
while
true
clear
getline
评论
ben_stokes.txt
for
eof()