c++ - 为什么我不能从文件中读取最后一个字符串?
问题描述
我可以阅读除最后一个“Yury Chen 88 3939202”之外的所有字符串
ifstream file("text.txt");
string s;
int counter = 0;
for(file >> s; !file.eof(); file >> s)
{
if (counter<=3){
templist.push_back(s);
counter +=1;
}
else{
list.push_back(templist);
counter = 0;
templist.clear();
templist.push_back(s);
counter +=1;
}
}
text.txt 是
John Jones 12 5412354
Kevin Abatsa 23 6431264
Name Surname 31 1239523
Yury Chen 88 3939202
问题出在哪里?
解决方案
问题可能在于:
for(file >> s; !file.eof(); file >> s)
当这流式传输文件中的最后一个字符串时3939202
- 它可能会设置eof
标志,因此您在不处理该字符串的情况下退出。(我们不能肯定地说,因为我们看不到3939202
您的文件中是否有空格......)。
只需更改为:
while (file >> s)
推荐阅读
- postgresql - 如果存在多个索引,Postgres 如何选择使用哪个索引?
- flutter - Flutter,设置多个堆栈的屏幕
- javascript - 如何在javascript中附加默认下拉选项值
- .htaccess - 通过 .htaccess 文件将 .png 图像重定向到另一个 .png 图像
- php - woocommerce 转换器时间戳 $orderdate = $order->order_date;
- java - 如何在 spark kafka 流中创建消费者组并将消费者分配给消费者组
- ruby - 如何在两个大浮点值相乘后得到正常值,从而导致 ruby 语言中的指数值?
- powershell - 如何将 Start-Job -ArgumentList 转换为正确的值
- wcf - ASP.net core 3.1 API 中的 WCF Rest 服务参考
- swift - 影响滚动视图的几何阅读器