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

Feb 27, 2015 at 2:25am
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 Mar 5, 2015 at 6:13pm
Feb 27, 2015 at 2:30am
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 Feb 27, 2015 at 2:31am
Topic archived. No new replies allowed.