Count the number of lines in a text file in C++

In the previous tutorial, we learned how to create a text file, how to open a text file and how to read a particular line from a text file, in this tutorial, we will learn about how to count the number of lines in a text file with the help of c++.

in my previous tutorial, we created a text file having two lines inside it, in this tutorial we use the same text file to count the number of lines.

How to count the number of lines in a text file in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int count = 0;

void number()
{
  count--;
    cout<<"number of lines : " << count << endl;

};

int main()
{
    string line;
    ifstream file("Codespeedy.txt");

    if(file.is_open())
  {
        while(!file.eof())
    {
            getline(file,line);
            cout<< line << endl;
            count++;
        }
        file.close();
    }
    number();

}

 

in the above piece of code, we create a number function to print the number of lines, in this code we use getline() function.  getline() function is a c++ liabrary function, used to read a line from file.

general synatx of getline():  getline(char *string, int length, char deliminator).

C++ provides a special function, eof(), that returns TRUE when there are no more data to read from an input file stream, and returns FALSE otherwise.
suppose we create a text file like Codespeedy.txt, having two lines:

  1. hello i am Raj Gaurav
  2. hello i am Raj Gaurav2.

when we apply this code the output will be like:

hello i am Raj Gaurav
hello i am Raj Gaurav2
number of lines : 2

Also read how to create a Text file, Open and Read:  File Handling

Do let me know in the comments section if you have any doubts.

Leave a Reply

Your email address will not be published. Required fields are marked *