简体   繁体   English

getline()读取额外的一行

[英]getline() reads an extra line

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";
      } 
}

I am using a two dimensional character array to keep the text (more than one line) read from a file to count the number of lines and words in the file but the problem is that getline always reads an extra line. 我正在使用二维字符数组来保持从文件中读取文本(多于一行)以计算文件中的行数和单词数,但是问题是getline总是读取额外的一行。

Your code as I'm writing this: 您在编写此代码时的代码:

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";
      } 
}

The first time getline fails, you still increment the line counter and output the (non-existing) line. 第一次getline失败时,您仍然会增加行计数器并输出(不存在)行。

Always check for an error. 始终检查错误。

extra advice: use std::string from the <string> header, and use its getline function. 额外建议:使用<string>标头中的std::string ,并使用其getline函数。

cheers & hth. 干杯和健康。

Only do the cout if file.good() is true. 仅当file.good()为true时才执行cout The extra line you're seeing comes from the last call to file.getline() which reads past the end of the file. 您看到的额外行来自对file.getline()的最后一次调用,该调用读取了文件末尾的内容。

The problem is when you're at the end of the file the test on file will still succeed because you have not yet read past the end of file. 问题是,当你在文件上的测试结束file仍然会成功,因为你还没有读取文件的末尾。 So you need to test the return from getline() as well. 因此,您还需要测试getline()的返回值。

Since you need to test the return from getline() to see if it succeeded, you may as well put it right in the while loop: 由于您需要测试getline()的返回值是否成功,因此您最好将它放在while循环中:

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

This way you don't need a separate test on file and getline() . 这样,您就不需要对filegetline()进行单独的测试。

This will solve your problem: 这将解决您的问题:

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";
  } 
}

Its more robust 它更强大

Does the file end with a newline? 文件是否以换行符结尾? If it does, the EOF flag will not be triggered until one extra loop passes. 如果确实如此,则只有经过一个额外的循环后,才会触发EOF标志。 For example, if the file is 例如,如果文件是

abc\n
def\n

Then the loop will be run 3 times, the first time it will get abc , the second time it will get def and the third time it will get nothing. 然后循环将运行3次,第一次将获得abc ,第二次将获得def ,第三次将什么也没有。 That's probably why you see an additional line. 这可能就是为什么您看到另外一行。

Try checking the failbit on the stream AFTER the getline. 尝试在getline之后检查流上的故障位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM