John Richards John Richards - 1 year ago 113
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?

Answer Source

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++;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download