Thread: Keeping track of words inputted

1. Keeping track of words inputted

Like the topic says I am trying to keep track of how many times a word is typed. I am using 2 vectors one to keep the unique words and another to hold the number of times each word has been typed in.
Code:
```#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::vector;

" int main(){
vector<string> word;
vector<int> number;
bool copy;int y,z;
string input;
vector<string>::size_type svec;

cout<< "enter a word"<< endl;
cin>>input;
number.push_back(1);
word.push_back(input);
cout<< "enter a word"<< endl;
while(cin>>input){int svec =0;
copy =false;
for(svec =0;svec<word.size();svec++)
{if(input==word[svec])
{copy=true; number[svec] +=number[svec]+1;}
}
if(!copy)                           {
word.push_back(input);
number.push_back(1);
}
}

y=number.size();
for(z=0;z<y;z++)
cout<<word[z]<< " " <<number[z] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}```
The above is what I have coded, when I input something like:
"bob
bob
bob
bob"
and then end input I get this: bob 15. I know there is something obvious that I'm not getting. Any help would be appreciated.

2. Code:
`number[svec] +=number[svec]+1;`
That's the problem, use = instead of +=.

With the += this is what you are doing:
Start with 1.
1 + 2 = 3
3 + 4 = 7
7 + 8 = 15
Get it?

Easier to use a map<string,int> container:

Code:
```#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::map;

int main()
{
string input;
map<string,int> words;
map<string,int>::const_iterator cit;

cout << "enter a word" << endl;
while( cin >> input )
words[input]++;

for( cit = words.begin(); cit != words.end(); ++cit )
cout<< cit->first << " " << cit->second << endl;

system("PAUSE");
return EXIT_SUCCESS;
}```
The words will be nicely sorted alphabetically for you as well using such a map.

3. Yes I see what you are saying. I must have gotten confused as I typed. Thanks for the help, I'll definatley look into maps and their usage.

Popular pages Recent additions