首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

[请问]C++ Primer 第四版 习题6.12

2012-02-26 
[请教]C++ Primer 第四版 习题6.12编写一个小程序:从标准输入读入一系列string对象,寻找连续重复出现的单

[请教]C++ Primer 第四版 习题6.12
编写一个小程序:从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。输出重复次数的最大值,若没有单词重复则输出说明信息。例如,如果输入是:
how,   now   now   now   brown   cow   cow
则输出应表明“now”这个单词出现了三次。

搞了很长时间不能理想地实现这个程序所要求的功能,总是存在或多或少的问题。哪位朋友能帮忙写一下让我学习学习,谢谢

[解决办法]
#include <string>
#include <iostream>
using namespace std;

int main() {
string lastWord;
string maxWord;
string word;

int count = 0;
int maxCount = 0;

while(cin > > word) {
if(word == lastWord) {
++count;
} else {
if(count + 1 > maxCount) {
maxWord = lastWord;
maxCount = count + 1;
}

count = 0;
lastWord = word;
}
}

if(maxCount <= 1) {
cout < < "No word repeated. " < < endl;
} else {
cout < < "Word [ " < < maxWord < < "] repeated for "
< < (maxCount) < < " time(s). " < < endl;
}

return 0;
}

热点排行