首页 > 解决方案 > 为什么我不能从文件中读取最后一个字符串?

问题描述

我可以阅读除最后一个“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

问题出在哪里?

标签: c++

解决方案


问题可能在于:

for(file >> s; !file.eof(); file >> s)

当这流式传输文件中的最后一个字符串时3939202- 它可能会设置eof标志,因此您在不处理该字符串的情况下退出。(我们不能肯定地说,因为我们看不到3939202您的文件中是否有空格......)。

只需更改为:

while (file >> s)

推荐阅读