C++Primer第五版 5.4.1节练习
练习5.14:编写一段程序,从标准输入中读取若干string对象并查找连续重复出现的单词。所谓连续重复出现的意思是:一个单词后面紧跟着这个单词本身。要求记录连续出现的最大次数以及对应的单词。如果这样的单词存在,输出重复出现的最大次数。如果不存在,输出一条信息说明任何单词都没有连续出现过。例如,如果输入是
how now now now brown cow cow
那么输出应该表明单词now连续出现了3次
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::cin;
int main(void)
{
vector<string> list;
string str;
unsigned Cnt=0,Cnt2=0;
while(cin>>str)
list.push_back(str);
list.push_back("fdfdl2;3d"); //循环需要
auto beg=list.begin();
string word=*beg,word2;
while(beg!=list.end())
{
if(word==*beg)
++Cnt;
else
{
if(Cnt2<=Cnt)
{
Cnt2=Cnt;
word2=word;
}
Cnt=0;
word=*beg;
continue;
}
++beg;
}
if(Cnt2<2)
cout<<"任何单词都没有连续出现过"<<endl;
else
cout<<"连续最多的单词"<<word2<<"连续出现了"<<Cnt2<<"次"<<endl;
return 0;
}