开发者

getline() reads an extra line

开发者 https://www.devze.com 2023-04-09 12:58 出处:网络
ifstream file(\"file.txt\"); if(file.fail()) { cout<开发者_如何转开发<\"Could not open the file\";
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.


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.

Always check for an error.

extra advice: use std::string from the <string> header, and use its getline function.

cheers & hth.


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. So you need to test the return from getline() as well.

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:

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

This way you don't need a separate test on file and getline().


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. 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. That's probably why you see an additional line.

Try checking the failbit on the stream AFTER the getline.


Only do the cout if file.good() is true. The extra line you're seeing comes from the last call to file.getline() which reads past the end of the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号