c++ - 从输入中查找连续出现的单词并且计数
给我你的怀抱
给我你的怀抱 2017-05-16 13:23:50
0
2
730

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

给我你的怀抱
给我你的怀抱

全部回复(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;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板