John Richards John Richards - 6 months ago 62
C++ Question

C++ fileIO line count

ifstream inFile;; //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?


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

size_t count = 0, i = 0, length = str.length();
    if(str[i]=='\n') count++;