调试 C++ Primer Exercise 5.14 的心得体会

题目:

Write a program to read strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated.

程序:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    
    
	string word_now;
	string word_last = "";
	vector<string> champion;
	int sum_last = 1;
	int sum_now = 1;
	while (cin >> word_now)
	{
    
    
		if (word_now == word_last)
			sum_now++; // the same word, count!
		else
		{
    
    
			if (sum_now > sum_last)
			{
    
    
				sum_last = sum_now;
				champion.clear();
				champion.push_back(word_last);
			} // now it is the largest, mop away the previous memory and write in new contents.
			else
			{
    
    
			    if (sum_now == sum_last)
				    champion.push_back(word_last);
			} // as large, its a champion as well as previous ones
			sum_now = 1;
		}
		word_last = word_now;
	}
	// Now test the last word.
	if (sum_now > sum_last)
	{
    
    
		sum_last = sum_now;
		champion.clear();
		champion.push_back(word_now);
	}
	else
	{
    
    
	    if (sum_now == sum_last)
		    champion.push_back(word_now);	
	}
	// output
	if (sum_last == 1) cout << "No word was repeated." << endl;
	else
	{
    
    
		if (champion.size() == 1) cout << "The max number of duplicates is " << sum_last << ".\nIt is:";
		else cout << "The max number of duplicates is " << sum_last << ".\nThey are:";
		for (auto c : champion) cout << c << " ";
		cout << endl;
	}
	return 0;
}

注:champion不一定只有一个!所以用 vector 存储。

一开始连续都只输出No word was repeated.,后来发现是忘记第30行内容。
启示:loop 进入新一轮准备工作要做好

后来输出champion的值时有时出现两个,发现是判断最后一词时忽略了顺序造成的影响。在37行sum_last = sum_now;的操作后,43行的 if 一定成立。
启示:要检查程序实际运行逻辑,改变参数要关注对之后内容的影响


【C++ Primer(5th Edition) Exercise】练习程序 - Chapter5(第五章)

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108280058
今日推荐