/*烟台大学计算机学院学生
*All right reserved.
*文件名称:用文件保存学生的名单
*作者:王洪海
*完成日期:2014年6月5日
*版本号:v1.0
*对任务及求解方法的描述部分:用文件保存学生的名单
*我的程序:*/
#include <iostream>
#include <fstream>
#include <string>
#include<cstdlib>
using namespace std;
class Student
{
public:
double get_total(); // 求单个学生总分
int get_stu_num(); // 等到学生的数量
double get_total_sum(); // 所有学生总分和
bool pass(double );
friend istream &operator >>(istream &in,Student &s);
friend ostream &operator <<(ostream &out,Student &s);
private:
string name;
double cpp;
double math;
double english;
double total;
static int stu_num; //学生人数,处理为类的静态静态成员合适
static double total_sum; //学生总分和
};
double Student::total_sum=0;
double Student::get_total()
{
total=cpp+math+english;
return total;
}
int Student::stu_num=0;
int Student::get_stu_num()
{
return stu_num;
}
double Student::get_total_sum()
{
return total_sum;
}
bool Student::pass(double avg)
{
if(total>=avg&&(cpp>=60)&&(math>=60)&&(english>=60))
return true;
else
return false;
}
istream &operator >>(istream &in,Student &s)
{
in>>s.name>>s.cpp>>s.math>>s.english;
s.total=s.cpp+s.math+s.english;
Student::stu_num++; //在读入数据过程中,用静态成员记录下来具体的学生人数和总分和
Student::total_sum+=s.total;
return in;
}
ostream &operator <<(ostream &out,Student &s)
{
out<<s.name<<"\t";
out<<s.cpp<<"\t";
out<<s.math<<"\t";
out<<s.english<<"\t";
out<<s.get_total()<<"\t";
return out;
}
int main()
{
Student stud[200],t;
double total_avg=0;
int i=0;
//string sname;
ifstream infile("score.txt",ios::in);
if(!infile)
{
cerr<<"date error!";
exit(0);
}
while(infile>>stud[i])
{
i++;
}
infile.close();
for(i=0;i<t.get_stu_num();i++)
{
double s=0;
s+=stud[i].get_total();
total_avg=s/t.get_stu_num();
}
ofstream outfile("pass_score.txt",ios::out);
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(0);
}
for(i=0;i<t.get_stu_num();i++)
{
if(stud[i].pass(total_avg))
outfile<<stud[i]<<endl;
}
outfile.close();
cout<<"请到 pass_score 文件中检查。"<<endl;
return 0;
}
运行结果,如下图:
运行前文件:
运行后文件: