search

Home  >  Q&A  >  body text

c++ - Find consecutive occurrences of words from input and count

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~

给我你的怀抱给我你的怀抱2748 days ago713

reply all(2)I'll reply

  • 为情所困

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

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

    wordAlso leave it blank.

    reply
    0
  • 为情所困

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

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

    reply
    0
  • Cancelreply