-4

I want to count number of lines in a file.But here I am getting the number of lines in file+1 as answer. For example, if my file has 2 lines then my code will give 3 as answer.

Here is my code-

int c=0;
void number()
{ 
   cout<<"NO. OF LINES :"<<c<<endl;
}
 
int main()
{
   string line;
   ifstream file("text1.txt");
   
   if(file.is_open())
   {
       while(!file.eof())
       {
           getline(file,line);
           cout<<line<< endl;
           c++;
        }
        file.close();
    }
    number();
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Read a good [C++ programming book](https://stroustrup.com/programming.html), this [C++ reference](https://en.cppreference.com/w/cpp), the documentation of your C++ compiler (e.g. [GCC](http://gcc.gnu.org/)...) and of your debugger (e.g. [GDB](https://www.gnu.org/software/gdb/)...). Your code is wrong (not some [mre]) since it does not contain any `#include` – Basile Starynkevitch Oct 10 '20 at 07:26

1 Answers1

2

Explicitly checking .eof() is usually the wrong thing to do. Instead, check the result of getline():

int main()
{
    string line;
    ifstream file("text1.txt");
   
    if(file)
    {
        while(getline(file,line))
        {
            cout<<line<< endl;
            c++;
        }
    }
    number();
}

.eof() only returns true when the file has been read "past the end," not when you have merely read all the content and no further. That's why you got one extra iteration--the one where getline() failed but you didn't check.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436