Kobe Kobe - 11 months ago 63
C++ Question

Read number of lines, words, characters from a file

I can read the number of lines easy, using:

ifstream in(file);
string content;
while(getline(in, content))
// do stuff

Or I can read the number of words and characters easy using something like:

ifstream in(file)
string content;
int numOfCharacters = 0;
int numOfWords = 0;
while(in >> content)
numOfCharacters += content.size();

But I dont want to read the file twice. How can I read the file once, and find out the number of lines, words and characters?

PS: I would welcome a Boost sugestion, if there is a easy way.

Thank you.

Answer Source

Read the line and for each line count the words. See stringstream for the second part.

(I'm not giving more information, that looks too much like an homework).