搜索

首页  >  问答  >  正文

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又感觉逻辑没什么问题,请各位指点指点,谢谢~

给我你的怀抱给我你的怀抱2752 天前718

全部回复(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
  • 取消回复