2017-04-13 78 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