c++ - 从输入中查找连续出现的单词并且计数

【字号: 日期:2023-03-21浏览:16作者:雯心

问题描述

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

问题解答

回答1:

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

word也要置空。

回答2:

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

相关文章: