Reputation: 953
I can compile the code with g++, as well as cin is good. However, I get no output after pressing Enter and I can continue inputting words. What's the problem?
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<string, size_t> word_count;
string word;
while (cin>>word) {
++word_count[word];
}
for (auto &w : word_count) {
cout<<w.first<<" occurs "<<w.second<<" times"<<endl;
}
return 0;
}
Upvotes: 0
Views: 118
Reputation: 23774
You did not specify how many words you want to be entered. And you are in infinite loop. So you can:
unsigned counter = 10; // enter 10 words
while ( cin >> word && --counter ) {
++word_count[word];
}
output:
zero
one
one
one
one
two
three
three
three
four
one occurs 4 times
three occurs 3 times
two occurs 1 times
zero occurs 1 times
Upvotes: 0
Reputation: 225
After doing some more research, I realized that the prior code I wrote was incorrect. You should not be using cin <<, rather you should be using getline(std::cin, std::string);
Your code should look like:
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<string, size_t> word_count;
string word;
while (getline(cin, word)) {
if(word.empty()) {
break;
}
++word_count[word];
}
for (auto &w : word_count) {
cout<<w.first<<" occurs "<<w.second<<" times"<<endl;
}
return 0;
}
Let me know if this causes any errors, I ran a few test cases and it seemed to work fine.
Upvotes: 1
Reputation: 1227
You need to send a EOF character, such as CTRL-D to stop the loop.
Upvotes: 4
Reputation: 189
while(cin>>word)
loops as long as you're entering a valid string. Empty string is still a valid string, hence the loop never ends.
Upvotes: 4