问题及代码:
/*
* Copyright (c)2015, 烟台大学计算机学院
* All rightsreserved.
* 文件名称: x.cpp
* 作者 : 李楠
* 完成日期: 2015年6月5日
* 版本号 : v1.0
* 问题描述: 文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。
(1)定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。
(2)用对象数组进行存储学生的成绩,读入成绩并计算总分;将总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中。
* 程序输出: 略
*/
#include <fstream>
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
class Student
{
public:
Student() {};
~Student();
double get_total();
static int get_stunum();
static double get_tsum();
friend istream& operator>>(istream &in, Student &s);
friend ostream& operator<<(ostream &out, Student &s);
bool pass();
private:
string name;
double cpp;
double math;
double english;
double total;
static int stunum; //学生人数,处理为类的静态成员合适
static double tsum; //学生总分和
};
int Student::stunum = 0;
double Student::tsum = 0;
Student::~Student()
{
tsum-=total;
stunum--;
}
double Student::get_total()
{
return total;
}
int Student::get_stunum()
{
return stunum;
}
double Student::get_tsum()
{
return tsum;
}
istream& operator>>(istream &in, Student &s)
{
in>>s.name>>s.cpp>>s.math>>s.english;
s.total=s.cpp+s.math+s.english;
Student::stunum++; //在读入数据过程中,用静态成员记录下来具体的学生人数和总分和
Student::tsum+=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.total;
return out;
}
bool Student::pass()
{
if(cpp>=60 && math>=60 && english>=60)
return true;
else
return false;
}
int main( )
{
Student stud[200],t;
double total_avg;
int i=0;
//将文件中的数据读入到对象数组中
ifstream infile("score.txt",ios::in); //以输入的方式打开文件
if(!infile) //测试是否成功打开
{
cerr<<"open error!"<<endl;
exit(1);
}
while(!infile.eof())
{
infile>>stud[i++]; //运算符重载
}
infile.close();
if(Student::get_stunum()>0)
{
total_avg = Student::get_tsum() / Student::get_stunum();
ofstream outfile("pass_score.txt",ios::out);
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0; i<Student::get_stunum(); i++)
{
if(stud[i].get_total()>total_avg&&stud[i].pass())
{
outfile<<stud[i]<<endl;
}
}
outfile.close();
cout<<"在文件pass_score.dat中查看名单:"<<endl;
}
return 0;
}
运行结果:
知识点总结:
类中的函数是重点,可以用运算符重载<<和>>也可以用函数输入输出来表示
学习心得:
这个星期的项目总有一种想拖着不写的冲动,难道是我太懒惰…