John Richards John Richards - 8 days ago 6
C++ Question

C++ fileIO line count

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?

Answer

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++;
Comments