Hi,
In C++, how can I count lines using the standard classes fstream, ifstream?
Thank you, Mohammad
Hi,
In C++, how can I count lines using the standard classes fstream, ifstream?
Thank you, Mohammad
You read the file line by line. Count the number of lines you read.
How about this :-
std::ifstream inFile("file");
std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n');
int numLines = 0;
ifstream in("file.txt");
//while ( ! in.eof() )
while ( in.good() )
{
std::string line;
std::getline(in, line);
++numLines;
}
There is a question of how you treat the very last line of the file if it does not end with a newline. Depending upon what you're doing you might want to count it and you might not. This code counts it.
This is the correct version of Craig W. Wright's answer:
int numLines = 0;
ifstream in("file.txt");
while ( std::getline(in, std::string()) )
++numLines;