C++ 为什么代码没有cout?

C++ 为什么代码没有cout?,c++,c++11,C++,C++11,我可以用g++编译代码,cin也不错。然而,我没有得到任何输出后,按回车键,我可以继续输入的话。有什么问题吗 #include<iostream> #include<string> #include<map> using namespace std; int main() { map<string, size_t> word_count; string word; while (cin>>word) {

我可以用g++编译代码,cin也不错。然而,我没有得到任何输出后,按回车键,我可以继续输入的话。有什么问题吗

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
映射字数;
字符串字;
while(cin>>word){
++字数;
}
用于(自动&w:字数计数){

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

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

在做了更多的研究之后,我意识到我之前编写的代码是不正确的。您不应该使用cin您没有指定有多少个w您希望输入的ORD。并且您处于无限循环中。因此您可以:

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

“代码没有cout”和“我没有cout”是什么意思?我在这段代码中看到了大量的
cout
用法。您不需要
if
语句;当输入为
EscapeSeSequence时,代码不会进入循环体
。有没有办法用一个“回车”键跳出循环?@zhaokai如果您将终止字符串更改为空字符串“”,那么当用户输入空字符串时(在没有输入的情况下按enter键),循环将结束。很抱歉,这似乎不是一个正确的解决方案。我尝试了空字符串“”用g++,但是 Ctrl +d</代码>还需要跳出。代码是从C++底漆中拷贝的,是不是错了?有没有办法按Enter字符作为Enter字符?
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