user971089
user971089

Reputation: 53

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.

Upvotes: 1

Views: 8507

Answers (5)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

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.

Upvotes: 4

Shravan
Shravan

Reputation: 2919

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

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100638

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().

Upvotes: 2

Kusalananda
Kusalananda

Reputation: 15603

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.

Upvotes: 1

Foo Bah
Foo Bah

Reputation: 26251

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.

Upvotes: 0

Related Questions