[英]Why the code has no cout?
我可以用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;
}
只要輸入有效的字符串, while(cin>>word)
循環。 空字符串仍然是有效字符串,因此循環永遠不會結束。
您需要發送EOF字符(例如CTRL-D)來停止循環。
經過更多研究之后,我意識到我編寫的先前代碼是錯誤的。 您不應該使用cin <<,而應該使用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;
}
讓我知道這是否會導致任何錯誤,我運行了一些測試用例,它似乎運行良好。
您未指定要輸入的單詞數。 而您處於無限循環中。 所以你可以:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.