C++ Primer 5.14

编写一段程序,从标准输入读取若干string对象并查找连续重复出现的单词。所谓连续重复出现的意思是:一个单词后面紧跟着这个单词本身。要求记录连续重复出现的最大次数以及对应的单词。如果这样的单词存在,输出重复出现的最大次数;如果不存在,输出一条信息说明任何单词都没有连续出现过。例如,如果输入是

how now now now brown cow cow

那么输出应该表明单词now连续出现了三次

# include <iostream>
# include <vector>
# include <string>
using namespace std;
using std::vector;
int main()
{
	string str,word,max_str;
	cin >> str;
	unsigned int max_num = 1,num=1;
	while (cin >> word)
	{
		if (word == str)
		{
			++num;
			if (num >= max_num)
			{
				max_num = num;
				max_str = word;
			}
			str = word;
		}
		else
		{
			num = 1;//重置计数器
			str = word;
		}
	}
	if (max_num != 1)
		cout << max_str << " appears " << max_num << " times " << endl;
	else
		cout << "There is no consecutive words!" << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Jason6620/article/details/88344772