C++ Get Total File Line Number

I'd do like this :

   ifstream aFile ("text.txt");   
   std::size_t lines_count =0;
   std::string line;
   while (std::getline(aFile , line))
        ++lines_count;

Or simply,

  #include<algorithm>
  #include<iterator>
  //...
  lines_count=std::count(std::istreambuf_iterator<char>(aFile), 
             std::istreambuf_iterator<char>(), '\n');

There is no such function. Counting can be done by reading whole lines

std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
    ;

A note about scope, variable i must be outside for, if you want to access it after the loop.


You may also read character-wise and check for linefeeds

std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
    if (c == '\n')
        ++i;

I fear you need to write it by yourself like this:

int number_of_lines = 0;
 std::string line;
 while (std::getline(myfile, line))
        ++number_of_lines;

 std::cout << "Number of lines in text file: " << number_of_lines;