c++ - 使用 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
发生?所以我们进入循环并读取EOF
eof-bit 和 fail-bit 设置正确吗?那么为什么它不会在下一次迭代中作为 eof 位集退出循环。
解决方案
调用clear
将重置eof
标志,因此while
-loop 的条件将始终评估为true
。clear
之前 调用getline
,代码将起作用。
推荐阅读
- javascript - 导航到延迟加载模块 Angular 8 的子节点
- mysql - 如何匹配同一张表的多个列并选择最大匹配列
- c# - 无法在下拉 selectedindexchange 中附加列表以供以后在 buttonclick 事件中使用
- spring - 使用 spring boot 应用程序在 ROMETOOL 上设置我的 RSS 提要
- python-3.x - 在 Python Selenium 中处理 reCAPTCHA
- python - django docker db migrations 不适用于新模型
- python - 反向查找 django 模型
- react-native - 来自 Firebase 推送通知的反应导航导航
- azure - Azure 功能不适用于 https,仅适用于 http
- node.js - Node.js Paypal 集成