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~
为情所困2017-05-16 13:25:50
if (temp > result)
{
result = temp;
temp = 0;
//!
word = "";
}
word
Also leave it blank.
为情所困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;
}