c++ - Find consecutive occurrences of words from input and count
给我你的怀抱
给我你的怀抱 2017-05-16 13:23:50
0
2
717

The question is to read several string objects from the standard input and find consecutive repeated words. For example, if the input is:
how now now now heaven cow
it should output 3 (now appears 3 consecutively Second-rate)

#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;
}

However, the problem now is that the output is always 0. I find the bug myself but feel that there is nothing wrong with the logic. Please give me some advice, thank you~

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

reply all(2)
为情所困
if (temp > result)
{
    result = temp;
    temp = 0;
    
    //!
    word = "";
}

wordAlso leave it blank.

为情所困

eg: Enter only one word or many words

Think comprehensively

#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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template