项目2 - 用文件保存的学生名单

/*
*作者:lws
*完成时间:2014/6/5
*问题描述:文件操作
*/
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
class Student
{
public:
	Student(){}
	double getCpp()
	{
		return cpp;
	}
	double getMath()
	{
		return math;
	}
	double getEnglish()
	{
		return english;
	}
	double getTotal()
	{
		return total;
	}
	int getStu_num()
	{
		return stu_num;
	}
	double getTotal_sum()
	{
		return total_sum;
	}
	friend istream &operator>>(istream &in,Student &p);
	friend ostream &operator<<(ostream &out,Student &p);
private:
	string name;
	double cpp;
	double math;
	double english;
	double total;
	static int stu_num; //学生人数,处理为类的静态成员合适
	static double total_sum; //学生总分和 
};
istream &operator>>(istream &in,Student &p)
{
	in>>p.name>>p.cpp>>p.math>>p.english;
	p.total+=p.cpp+p.math+p.english;
	p.stu_num++;
	p.total_sum+=p.total;
	return in;
}
ostream &operator<<(ostream &out,Student &p)
{
	out<<"学生姓名"<<"  "<<"c++成绩"<<"  "<<"数学成绩"<<"  "<<"英语成绩"<<endl
		<<p.name<<setw(8)<<p.cpp<<setw(8)<<p.math<<setw(8)<<p.english;
	return out;
}
int Student::stu_num=0;
double Student::total_sum=0;
int main()
{
	Student stud[200],t;//stud[200]为保存数据的对象数组
	string sname;
	double total_avg;
	int i=0;
	//从文件score.dat中读入数据,保存到对象数组中
	ifstream input("score.dat",ios::in);
	if(!input)
	{
		cerr<<"open erorr!"<<endl;
		exit(1);
	}
	for(i=0;i!=200;i++)
	{
		input>>stud[i];
	}
	input.close();
	//总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中 
	ofstream output("pass_score.dat",ios::out);
	if(!output)
	{
		cerr<<"open erorr!"<<endl;
		exit(1);
	}
	for(i=0;i!=200;i++)
	{
		total_avg=stud[i].getTotal_sum()/stud[i].getStu_num();
		if(stud[i].getTotal()>total_avg&&stud[i].getCpp()>60&&stud[i].getMath()>60&&stud[i].getEnglish()>60)
		{
			output<<stud[i]<<endl;
		}
	}
	output.close();
	return 0;
}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值