Word counting progam - how to deal with multiple spaces between words?

I am new to programming, and one of our first assignments is to produce a program that counts the number of words and number of lines from a file. I have the word counter set up to count spaces or new lines to determine how many words there are. This becomes a problem if there is more than one space between words. Any ideas how to fix this problem? Thanks!

Last edited on
If you use formatted input, you do not have to worry about this at all. The formatted input operators already read single words at a time.
1
2
3
4
5
6
7
8
9
10
if(std::ifstream in ("in.txt"))
{
    int words = 0;
    std::string word;
    while(in >> word)
    {
        ++words;
    }
    std::cout << "The file contained " << words << " words" << std::endl;
}
Hint: if you still need to count lines, you can always put the line into a std::istringstream and then use the above code.
Last edited on
Topic archived. No new replies allowed.