ccpp5 編程練習6.6

// ex6.6
// 考慮了錯誤輸入的狀況
#include <iostream>
#include <string>
using namespace std;
struct donor {
	string name;
	double amount;
};

int main ()
{
	int num = -1; // number of contributors
	cout << "Enter the number of contributors: ";
	// 注意獲得 int 值後要吞掉換行符
	// num 輸的不對,則反覆
	while (1) {
		if (!(cin >> num).get() || num < 0)
			cout << "Enter the number of contributors: ";
		else
			break;
	}

	// 0 我的,直接退出
	if (num == 0)
	{
		cout << "Well, 0.\nBye!\n";
		return 1;
	}

	donor * Mydonor = new donor [num];  // 分配內存
	cout << "Please enter the name and contribution of each contributor.\n";

	for (int i = 0; i < num; i++)
	{
		cout << "Contributor #" << i+1 << ":\n";
		cout << "Name: ";
		// 沒獲得名字的話,循環
		while (getline(cin, Mydonor[i].name)) {
		       	if (Mydonor[i].name.size() == 0) {
				cout << "Name: ";
			} else
				break;
		}
		cout << "Contribution: $";
		// 須要 cin.clear() 先重置輸入,不然可能死循環之類狀況,理解得不清楚
		// 輸入不對,則循環
		while (1) {
			if (!(cin >> Mydonor[i].amount) || Mydonor[i].amount <= 0) {
				cin.clear(); // reset input
				while (cin.get() != '\n')
					continue; // get rid of bad input
				cout << "Contribution: $";
			} else
				break;
		}
		cin.get(); // 吞掉換行

	}
//----------------------------------------------------------
	cout << "\nGrand Patrons\n----------\n";
	int count = 0;    // 統計,檢查是否 0 個
	for (int i = 0; i < num; i++)
	{
		if (Mydonor[i].amount >= 10000)
		{
			cout << Mydonor[i].name << ": $" 
			     << Mydonor[i].amount << endl;
			++count;
		}
	}
	if (count == 0)
		cout << "none\n";

//----------------------------------------------------------                   cout << "\nPatrons\n---------\n";
        if (count < num)
	{
		//count = 0;
		
		for (int i = 0; i < num; i++)
		{
			if (Mydonor[i].amount < 10000)
			{
				cout << Mydonor[i].name << ": $" 
				     << Mydonor[i].amount << endl;
				//++count;
			}
		}
		//if (count == 0)
		//	cout << "none\n";
	}
	else
		cout << "none\n";

	delete [] Mydonor;
	return 0;
}
相關文章
相關標籤/搜索