搜尋

首頁  >  問答  >  主體

c++ - 從輸入中尋找連續出現的單字並且計數

題目是從標準輸入中讀取若干個string物件並且查找連續重複出現的單字,例如如果輸入是:
how now now now heaven cow
就應該輸出3(now連續出現了3次)

#include "iostream"
#include "string"

using namespace std;

int main() {
    int result = 0;
    int temp = 0;

    string word = "";
    string tempWord = "";

    cout << "Enter a bunch of words: " << endl;
    while (cin >> tempWord) {
        if (word == "") {
            word = tempWord;
            ++temp;
        }
        else {
            if (tempWord == word) {
                ++temp;
            }
            else {
                if (temp > result) {
                    result = temp;
                    temp = 0;
                }
            }
        }
    }
    cout << result << endl;

    return 0;
}

然而現在的問題是輸出一直是0,自己找bug又感覺邏輯沒什麼問題,請各位指點指點,謝謝~

给我你的怀抱给我你的怀抱2748 天前712

全部回覆(2)我來回復

  • 为情所困

    为情所困2017-05-16 13:25:50

    if (temp > result)
    {
        result = temp;
        temp = 0;
        
        //!
        word = "";
    }

    word也要置空。

    回覆
    0
  • 为情所困

    为情所困2017-05-16 13:25:50

    eg: 只輸入一個單字 很多單字

    考慮全面

    #include<iostream>
    #include<string>
    using namespace std;
    int main() {
        int result = 0;
        int temp = 0;
    
        string word = "";
        string tempWord = "";
    
        cout << "Enter a bunch of words: " << endl;
        while (cin >> tempWord) {
            if (word == "") {
                word = tempWord;
                ++temp;
                if (temp > result) {
                    result = temp;
            }
    
            }
            else {
                if (tempWord == word) {
                    ++temp;
                    if (temp > result) {
                           result = temp;
                }
                }
                else {    
            word = tempWord;
            temp = 1;
                }
            }
        }
        cout << result << endl;
    
    return 0;
    }

    回覆
    0
  • 取消回覆