1
ifstream inFile;
inFile.open(filename); //open the input file

stringstream strStream;
strStream << inFile.rdbuf(); //read the file

string str = strStream.str(); //str holds the content of the file

I am using this code to read from a file. I need to get the number of lines at that file. Is there a way of doing that without reading the file second time?

  • 1
    Possible duplicate of [C++ Get Total File Line Number](http://stackoverflow.com/questions/19140148/c-get-total-file-line-number) – rbaleksandar Nov 26 '16 at 22:38

3 Answers3

3

You already have the contents in a string, so just inspect that string:

size_t count = 0, i = 0, length = str.length();
for(i=0;i<length;i++)
    if(str[i]=='\n') count++;
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
2

I would be tempted to do this:

auto no_of_lines = std::count(str.begin(), str.end(), '\n');
Galik
  • 47,303
  • 4
  • 80
  • 117
1

std::count which is in algorithm library helps you.

#include <algorithm>
#include <iterator>

//...

long long lineCount { std::count(
        std::istreambuf_iterator<char>(inFile),
        std::istreambuf_iterator<char>(),
        '\n') };

std::cout << "Lines: " << lineCount << std::endl;
  • Not totally correct. `std::count` returns `Iterator::difference_type`, which in this case is `std::char_traits::off_type` and that type is implementation defined. My point is that you should use `auto` and not `long long` if you want to make sure the right return type is used. – Blazo Nov 27 '16 at 01:15