簡體   English   中英

為什么我的 c++ 代碼沒有顯示任何 output?

[英]Why does my c++ code does not show any output?

我正在學習 c++ 入門書並做練習 5.14。 練習是:

編寫一個程序從標准輸入中讀取字符串以查找重復的單詞。 程序應該在輸入中找到一個單詞緊隨其后的位置。 跟蹤單個重復出現的最大次數以及重復哪個單詞。 打印最大重復數,或者打印一條消息,說明沒有重復單詞。 例如,如果輸入是 how now now now brown cow cow,則 output 應該指示單詞 now 出現了 3 次。

我的代碼如下:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string pre_word, word, max_repeate_word;
int repeate_times = 0; max_repeate_times = 0;
while (cin >> word) {
    if (word == pre_word) {
        ++repeat_times;
    }
    else {
        repeat_times = 1;
        pre_word = word;
    }

    if (max_repeat_times < repeat_times) {
        max_repeat_times = repeat_times;
        max_repeat_word = pre_word;
    }
}

if (max_repeat_times <= 1) {
    cout << "no word was repeated" << endl;
}
else {
    cout << "the word '" << max_repeat_word << "' occurred " << max_repeat_times << " times" << endl;
}
}

我的代碼有什么問題嗎? 當我輸入任何字符串時,程序不顯示任何 output。

while (cin >> word)

這個停止只有EOF,你需要添加一個停止條件。 例子:

while (cin >> word && word != "")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM