循环读取文件中的字符串和数字
题目
编写一个程序,记录捐助给“维护合法权利团体”的资金。
该程序要求从文件中读取捐献者数目,和每一个捐献者的姓名和款项。
这些信息被储存在一个动态分配的结构数组中。
每个结构有两个成员:
用来储存姓名的字符数组(或string对象)和用来存储款项的double成员。
读取所有的数据后,程序将显示所有捐款超过10000的捐款者的姓名及其捐款数额。
该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。
然后,程序将列出其他的捐款者,该列表要以Patrons开头。
如果某种类别没有捐款者,则程序将打印单词“none”。
该程序只显示这两种类别,而不进行排序。
读取的文件格式
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int nameSize = 50;
struct donate {
string name;
int money;
};
int main()
{
char filename[20];
ifstream inFile;
cout << "Enter name of data file: ";
cin.getline(filename, 20);
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
int num = 0;
inFile >> num;
inFile.get();
donate *dd = new donate[num];
for (int i = 0; i < num; i++)
{
getline(inFile, dd[i].name);
inFile >> dd[i].money;
inFile.get();
}
// 检测文件是否成功
if (inFile.eof())
{
cout << "End of file reached.\n";
}
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
inFile.close();
// 打印结果
cout << "*******************Grand Patrons*******************" << endl;
int flag = 0;
for (int i = 0; i < num; i++)
{
if (dd[i].money > 10000)
{
cout << dd[i].name << ":\t" << dd[i].money << endl;
flag = 1;
}
}
if (flag == 0)
{
cout << "none!" << endl;
}
cout << "*****************Grand Patrons END******************" << endl;
cout << "*******************Patrons**************" << endl;
flag = 0;
for (int i = 0; i < num; i++)
{
if (dd[i].money <= 10000)
{
cout << dd[i].name << ":\t" << dd[i].money << endl;
flag = 1;
}
}
if (flag == 0)
{
cout << "none!" << endl;
}
cout << "*******************Patrons END**************" << endl;
system("pause"); //window使用后暂停
return 0;
}