Experience in debugging C++ Primer Exercise 5.14

topic:

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.

program:

#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;
}

Note: There is not necessarily only one champion! So use vector storage.

At first, it only output continuously No word was repeated., but later found out that the 30th line was forgotten.
Enlightenment: Preparations for loop entering a new round must be done well .

Later, when outputting the value of champion, there were two sometimes, and it was found that the influence of order was ignored when judging the last word. After sum_last = sum_now;the operation on line 37 , the if on line 43 must be established.
Enlightenment: To check the actual operation logic of the program, change the parameters to pay attention to the impact on the subsequent content .


[C++ Primer(5th Edition) Exercise] Exercise Program-Chapter5 (Chapter 5)

Guess you like

Origin blog.csdn.net/weixin_50012998/article/details/108280058