題目是從標準輸入中讀取若干個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又感覺邏輯沒什麼問題,請各位指點指點,謝謝~
为情所困2017-05-16 13:25:50
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;
}