2017-04-13 103 views
0

我可以用g ++编译代码,以及cin也不错。但是,在按输入后我没有输出,我可以继续输入单词。有什么问题?为什么代码没有cout?

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

你是什么意思 “的代码有没有COUT” 和 “我没有得到任何COUT”?我在这段代码中看到了'cout'的大量用法。 –

回答

4

while(cin>>word)只要你输入一个有效的字符串。空字符串仍然是一个有效的字符串,因此循环永远不会结束。

4

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

+0

有什么方法可以按输入作为EOF字符? – zhkai

1

在做了一些更多的研究后,我意识到我写的前面的代码是不正确的。你不应该使用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; 

}

让我知道这是否会导致任何错误,我跑了几个测试案例,它似乎做工精细。

+1

你不需要'if'语句;当输入是“escapeSequence”时,代码不会进入循环体。 –

+0

有没有办法通过单个“回车”跳出循环? – zhkai

+0

@zhaokai如果您将终止字符串更改为空字符串“”,那么当用户输入一个空字符串时(通过按下无输入的回车键),循环将结束。 –

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