Skip to main content
3 of 3
edited tags
200_success
  • 144.2k
  • 22
  • 188
  • 473

Counting the number of distinct words in the input

Below is a working program I wrote. Please provide comments to help me improve my coding and problem solving skills. I am learning C++ myself by reading Accelerated C++ by Andrew Koenig.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> words;
    cout<<"Please Enter words(Press Ctrl+Z in the end)"<<endl;

    string x; //Word Input
    cin>>x;
    words.push_back(x); //The first word
    int ndw=1; //Number of distinct words

    while(cin>>x) //Input new word
    {
        for(unsigned int counter = 0; counter!=words.size(); ++counter)
        {
            //Check if we already have this word in our list
            if(x!=words[counter])
            {
                if(counter==words.size()-1)//We have reached the end of list
                {
                    words.push_back(x);
                    ndw+=1;
                }
            }
            else
            {
                //If there is a match, leave this word
                break;
            }
        }
    }
    cout<<"number of distinct words are: "<<ndw;
    return 0;
}

Here is a sample output

Sample Output 1

Another Sample output

enter image description here