为什么代码没有cout?

时间:2017-04-13 13:51:48

标签: c++ c++11

我可以使用g ++编译代码,以及cin是好的。但是,按 Enter 后我没有输出,我可以继续输入单词。有什么问题?

#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;
}

4 个答案:

答案 0 :(得分:4)

只要您输入有效字符串,

while(cin>>word)就会循环播放。空字符串仍然是一个有效的字符串,因此循环永远不会结束。

答案 1 :(得分:4)

您需要发送EOF字符,例如CTRL-D以停止循环。

答案 2 :(得分:1)

在做了一些研究之后,我意识到我写的先前代码是不正确的。你不应该使用cin&lt;&lt;,而应该使用getline(std :: cin,std :: string);

您的代码应如下所示:

 #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;

}

如果这导致任何错误,请告诉我,我运行了一些测试用例,似乎工作正常。

答案 3 :(得分:0)

您没有指定要输入的字数。你处于无限循环中。所以你可以:

unsigned counter = 10;  // enter 10 words

while ( cin >> word && --counter ) {
    ++word_count[word];
}  

输出:

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