//输入文件名,文件内第一行为人数,接下来是姓名和金额。
#include<iostream>
#include<fstream> //文件输出,也要用名称空间std;
#include<cstdlib> //支持exit()
struct inflatable //结构体
{
char name[80];
double money;
};
int main()
{
int number,i,j=0,k=0;
char filename[60];
using namespace std;
ifstream inFile; //声明ifstream变量
cout <<"Please enter filename: ";
cin.getline(filename,60);
inFile.open(filename);//将ifstream对象和文件链接起来
if(!inFile.is_open()) //检查文件是否成功打开
{
cout <<"Could not open the file "<<filename<<endl;
cout <<"program terminating.\n";
//cin.get();
exit(EXIT_FAILURE); //终止程序
}
cout <<"Please enter donor number:";
inFile >>number; //确定动态结构数组的元素数
inflatable *p_donnor = new inflatable[number]; //声明动态数组
for(i=0;i<number;i++) //输入捐献者信息
{
cin.get();
cout <<"Please enter the "<<i+1<<" donnor information:\n";
cout <<"Patron: ";
inFile.getline(p_donnor[i].name,80);
cout <<"Money: ";
inFile >>p_donnor[i].money;
}
if(inFile.eof()) //输入结束检查。结束检查。只能检查时候遇到EOF,遇到返回ture
{
cout <<"End of file reached.\n";
}
else if(inFile.fail())//输入结束检查。检查类型不匹配和EOF,遇到返回false
{
cout <<"Input terminated by data mismatch.\n";
}
cout <<"\n\nGrand Patrons:\n";
for(i=0;i<number;i++) //筛选重要捐献者
{
if(p_donnor[i].money > 10000.0)
{
cout <<p_donnor[i].name<<"\t"<<p_donnor[i].money<<endl;
j++;
}
}
if(j==0) //是否有重要捐献者
cout <<" none\n";
cout <<"\nPatrons:\n";
for(i=0;i<number;i++)
{
if(p_donnor[i].money <= 10000.0)
{
cout <<p_donnor[i].name<<"\t"<<p_donnor[i].money<<endl;
k++;
}
}
if(k==0)
cout <<" none\n";
inFile.close(); //关闭文件
//cin.get();
return 0;
}
【C++】文件输入并处理动态数组
最新推荐文章于 2023-04-11 16:35:15 发布