从输入中查找连续出现的单词并且计数

题目是从标准输入中读取若干个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又感觉逻辑没什么问题,请各位指点指点,谢谢~

阅读 3.5k
2 个回答
if (temp > result)
{
    result = temp;
    temp = 0;
    
    //!
    word = "";
}

word也要置空。

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;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题