### Program to count the number of specific words in a string

Basically the program is meant to have the user input a string and then count each time a number is used and then print it out. The problem I'm having is that when the program prints out the results, it will have certain words appearing more than once, based on how many times they appear in the string.
For example if I input hello hello hi hey hey, the program will print out:
hello 2
hello 2
hi 1
hey 2
hey 2
The output I'm aiming for is:
hello 2
hi 1
hey 2

 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include using namespace std; struct Word { string word; int cnt; }; int main() { int passageSize; Word allwords[200]; for(int z=0;z<200;z++) allwords[z].cnt=0; for(int i=0;i<200;i++) { cin>>allwords[i].word; if(cin.eof()) break; } for(int a=0;a<200;a++) for(int b=0;b<200;b++) if(allwords[a].word==allwords[b].word) allwords[a].cnt++; for(int d=0;d<200;d++) { if(allwords[d].word=="") break; cout<
std::map. Map holds a key and a value. Keys are unique. When you get a word, check the map.

* If map has no such key, add the word as key and set the value to 1.
* If map has that key already, increase the value by one.

Alternatively, apply similar idea to your current algorithm.
The problem is in this loop

 ``1234`` `````` for(int a=0;a<200;a++) for(int b=0;b<200;b++) if(allwords[a].word==allwords[b].word) allwords[a].cnt++;``````

For example let assume that allwords[0].word contains word "Hello". According to the condition

allwords[a].word==allwords[b].word

we will have

allwords[0].word==allwords[0].word

and allwords[a].cnt will be incremented though there is only one word "Hello" in the array.

I would simplify your code the following way. The array can be initialized when it is defined.

Word allwords[200] - {};

In this case you need no the loop

 ``12`` `````` for(int z=0;z<200;z++) allwords[z].cnt=0;``````

In the loop where words are entered you can check whether a word is already is in the arrray. There is no need to store all words in the array because your task is different. You need only count the occurence of each word in the input stream.

Last edited on
thanks guys, great help.
Topic archived. No new replies allowed.