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