Input terminal problems and map
I am using map to count the 开发者_JAVA百科occurence of words. Here is the code.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string,int>wordcount;
string s;
while (cin>> s && s!="red")
++wordcount[s];
while (cin>>s && s!="red")
cout << s << " " << wordcount[s] << endl;
return 0;
}
I start the program, type words and at the last line enter the word "red", but it does not do anything. Then I type "red" the second time and it outputs:
press any key to continue
what is wrong?
Nothing is wrong. Visual Studio will automatically PAUSE
the program before it ends to prevent the console window from closing, when you "Run without Debugging".
I understand that you want to receive a list of words, fill each word's number of occurrences into a map, and print it.
So, instead of the second while loop, you need to iterate on the map that you created and print the count for each word.
You can learn here how to print the map's contents.
Too groggy to write here, but I'll try a second time. :)
If you write a lot of words, it will count them up until you write "red". The second loop will print the count for the words you input, but if you put "red" right away it will simply terminate the program without printing anything.
Try running the program with the following input:
one
two
two
red
zero
one
two
red
精彩评论