:) Hi, I'm a newbie here. I just want to know how to change this code so it can count word instead of letter

code:

#include <iostream>
#include <fstream>

using namespace std;

// count letters 'a' to 'z' in string s
void countLetters( string s )
{
        int pos, sum = 0;
        char m;

        // only a to z
        for( m = 97; m < 123; m++ )
        {
                // start with index = 0
                pos = s.find( m, 0 );
                while( pos != string::npos )
                {
                        // adjust index up
                        pos = s.find( m, pos+1 );
                        // total up this character
                        sum++;
                }
                if ( sum > 0)
                {
                        cout << m << " = " << sum << endl;
                }
                sum = 0;
        }
}

int main()
{
        char c;
        string str1,word,ch;
        ifstream is;

        is.open("input.txt");
        
      //   loop while extraction from file is possible
        while ( is.good() ) {
                // get character from file
                c = is.get();
                cout << c;
                // build string with all lower case characters
                c = tolower( c );
                str1.push_back( c );
        }
        cout << endl << endl;
        cout << str1 << endl;
        // count letters a to z
        countLetters(str1);

        // close file
        is.close();

        cin.get(); // wait
        return 0;
}

<< moderator edit: added [code][/code] tags >>


Really appreciate if somone can help me. Thanks....

Here's a hint:

Words are defined by spaces. Ergo, count spaces, and you can count words.

Here's another hint. (using underscores _ to represent spaces)
What's the difference between "It_is" and "It______is"?

This article has been dead for over six months. Start a new discussion instead.