Getline()读取额外的行

getline() reads an extra line

本文关键字:读取 Getline      更新时间:2023-10-16
ifstream file("file.txt");
 if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
      while(file)
      {
        file.getline(line[l],80); 
                          cout<<line[l++]<<"n";
      } 
}

我使用二维字符数组来保持从文件中读取的文本(多于一行),以计算文件中的行数和单词数,但问题是getline总是读取额外的行。

你的代码,因为我写这个:

ifstream file("file.txt");
 if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
      while(file)
      {
        file.getline(line[l],80); 
        cout<<line[l++]<<"n";
      } 
}

第一次getline失败时,仍然增加行计数器并输出(不存在的)行。

总是检查是否有错误。

额外建议:使用<string>头中的std::string,并使用其getline功能。

干杯,hth .

问题是当您在文件的末尾时,对file的测试仍然会成功,因为您还没有读取过文件的末尾。因此,您还需要测试getline()的返回值。

由于需要测试getline()的返回是否成功,因此不妨将其直接放在while循环中:

while (file.getline(line[l], 80))
    cout << line[l++] << "n";

这样你就不需要对filegetline()进行单独的测试。

这将解决您的问题:

ifstream file("file.txt");
if(!file.good())
{
  cout<<"Could not open the file";
  exit(1);
}
else
{
  while(file)
  {
    file.getline(line[l],80);
       if(!file.eof())
          cout<<line[l++]<<"n";
  } 
}

它更健壮

文件是否以换行符结束?如果是,EOF标志将不会被触发,直到一个额外的循环通过。例如,如果文件是

abcn
defn

然后循环将运行3次,第一次它将获得abc,第二次它将获得def,第三次它将一无所获。这可能就是为什么您会看到额外的一行。

尝试检查getline后流的failbit

仅在file.good()为真时执行cout。您看到的额外行来自对file.getline()的最后一次调用,它读取了文件的末尾。