天天看點

C++ primer(第五版) 練習 5.14 個人code



C++ primer(第五版) 練習 5.14

題目:編寫一段程式,從标準輸入中讀取若幹 string對象并查找連續重複出現的單詞。所謂連續重複出現的意思是:一個單詞後面緊跟着這個單詞本身。要求記錄連續重複出現的最大次數以及對應的單詞。如果這樣的單詞存在,輸出重複出現的最大次數;如果不存在,輸出一條資訊說明任何單詞沒有連續出現過。例如,如果輸入是:

how now now now brown cow cow

那麼輸出應該表明單詞now連續出現了3次。

答:

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;


int main()
{
	string str = {}, tmpstr1 = {}, tmpstr2 = {};
	unsigned cnt = 0,tmpcnt=0;
	cin >> str;
	tmpstr1 = str;
	while (cin >> str)
	{
	
		if (str == tmpstr1)
		{
			++cnt;
		}
		else
		{
			if (tmpcnt < cnt)
			{
				tmpcnt = cnt;
				tmpstr2 = tmpstr1;
			}
			cnt = 1;
		}
		tmpstr1 = str;
	
	}
	if (tmpcnt == 1)
	{
		cout << "任何單詞都沒有連續出現過" << endl;
	}
	else
	{
		cout << tmpstr2 << "連續出現次數最多,次數為:" << tmpcnt << endl;
	}	

	return 0;
}
           

執行結果:

C++ primer(第五版) 練習 5.14 個人code