exercise6_9.cpp
来源: 分支语句和逻辑运算符
点击上方按钮打开代码编辑器和可视化视图
⚠️ 交互式运行提示
为了防止网页挂起,所有 cin 输入语句已被自动注释。请直接在代码编辑器中修改变量的值来进行测试。
课后练习参考答案
原始代码预览
// Create by Shujia Huang on 2021-08-04
#include <iostream>
#include <fstream>
#include <string>
int main() {
using namespace std;
const int Grand_Amount = 10000;
string file_name;
ifstream in_file_handle;
struct Patron {
string name;
double amount;
};
int contribute_num = 0;
cout << "Enter a file name: ";
getline(cin, file_name); // 读一整行,行末回车符排除
in_file_handle.open(file_name.c_str());
in_file_handle >> contribute_num;
in_file_handle.get(); // 读掉空白(包括滞留在行末的回车符)
Patron *p_contribution = new Patron [contribute_num];
for (int i = 0; i < contribute_num; ++i) {
/*
* 4 Sam Stone
* 2000
* Freida Flass
* 100500
* Tammy Tubbs
* 5000
* Rich Raptor
* 55000
*
*/
getline(in_file_handle, p_contribution[i].name);
in_file_handle >> p_contribution[i].amount;
in_file_handle.get(); // 读掉空白(包括滞留在行末的回车符)
}
in_file_handle.close();
unsigned int grand_amount_n = 0;
cout << "\nGrand patron: " << endl;
for (int i = 0; i < contribute_num; ++i) {
if (p_contribution[i].amount > Grand_Amount) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
++grand_amount_n;
}
}
if (grand_amount_n == 0) {
cout << "None" << endl;
}
bool is_empty = true;
cout << "\nPatrons: " << endl;
for (int i=0; i < contribute_num; ++i) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
is_empty = false;
}
if (is_empty) {
cout << "** None **" << endl;
}
delete [] p_contribution;
return 0;
}
运行结果 / 调试信息
等待编译...
Graph loading...
0 / 0