C++ PRIMER中文版 page 179
题目: 从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现它本身。跟踪重复次数最多的单词及其重复次数。输出重复次数的最大值,若没有单词重复则输出说明信息。例如,如果输入是:
how, now now now brown cow cow
则输出应表明“now” 出现了三次
/**/
/*
Name: none
Copyright: none
Author: LK
Date: 04-08-06 13:00
Description: input a sequence of string objects,find out the word which appeared most frequently.
*/
#include < iostream >
#include < string >
#include < conio.h >
using namespace std;
int main()
... {
int tmp_cnt = 1, max_cnt = 1;
string word, tmp_word, max_word;
cin >> word;
tmp_word = word;
while(cin >> word) ...{
if(tmp_word != word) ...{
tmp_cnt = 1;
}
else ...{
++tmp_cnt;
}
if(tmp_cnt > max_cnt) ...{
max_cnt = tmp_cnt;
max_word = tmp_word;
}
tmp_word = word;
}
if(max_cnt == 1) ...{
cout << "therer is no repeated word." << endl;
}
else ...{
cout << max_word << " appears " << max_cnt << " times." << endl;
}
getch();
return 0;
}
Name: none
Copyright: none
Author: LK
Date: 04-08-06 13:00
Description: input a sequence of string objects,find out the word which appeared most frequently.
*/
#include < iostream >
#include < string >
#include < conio.h >
using namespace std;
int main()
... {
int tmp_cnt = 1, max_cnt = 1;
string word, tmp_word, max_word;
cin >> word;
tmp_word = word;
while(cin >> word) ...{
if(tmp_word != word) ...{
tmp_cnt = 1;
}
else ...{
++tmp_cnt;
}
if(tmp_cnt > max_cnt) ...{
max_cnt = tmp_cnt;
max_word = tmp_word;
}
tmp_word = word;
}
if(max_cnt == 1) ...{
cout << "therer is no repeated word." << endl;
}
else ...{
cout << max_word << " appears " << max_cnt << " times." << endl;
}
getch();
return 0;
}
缺陷:如果有同样满足要求的次数的单词出现,只会显示最先出现的那个
使用数组(OR vector<string>)存储可以解决这个问题
回来再说吧