第十四周 项目2-用文件保存的学生名单

来源:互联网 发布:淘宝网大型儿童跳跳床 编辑:程序博客网 时间:2024/04/30 00:26
/*  * Copyright (c) 2014, 烟台大学计算机学院  * All rights reserved.  * 文件名称:test.cpp  * 作    者:呼亚萍  * 完成日期:2015年6月10日  * 版 本 号:v1.0  *  * 问题描述: 文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。用对象数组进行存储学生的成绩,读入成绩并计算总分;将总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中。 * 程序输入:相应的程序 * 程序输出:对应得结果 */ #include<iostream>#include<fstream>#include<cstdlib>#include<cstring>using namespace std;class Student{public:    Student(){};    ~Student();    double get_total();    static int get_stu_num();    static double get_total_sum();    friend istream& operator>>(istream&,Student&);    friend ostream&operator<<(ostream&,Student&);    bool pass();//返回是否全部课程全过private:    string name;    double cpp;    double math;    double english;    double total;    static int stu_num;  //学生人数,处理为类的静态成员合适    static double total_sum; //学生总分和};int Student::stu_num=0;double Student::total_sum=0;Student::~Student(){    total_sum-=total;    stu_num--;//析构函数的释放}double Student::get_total(){    return total;}int Student::get_stu_num()//静态函数定义是需注明static{    return stu_num;}double Student::get_total_sum(){    return total_sum;}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.total<<'\t';    return out;}bool Student::pass(){    return (cpp>=60&&math>=60&&english>=60);}int main( ){    Student stud[200],t; //stud[200]为保存数据的对象数组    string sname;    double total_avg;    int i=0;    fstream infile,outfile;    infile.open("score.dat",ios::in);//从文件score.dat中读入数据,保存到对象数组中    if(!infile)    {        cout<<"score.dat can't open"<<endl;        exit(1);    }    while(!infile.eof())    {        infile>>stud[i++];    }    infile.close();    outfile.open("pass_dat.dat",ios::out);//总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中    if(Student::get_stu_num()>0)    {        total_avg=Student::get_total_sum()/Student::get_stu_num();        if(!outfile)        {            cout<<"can't open the file"<<endl;            exit(1);        }        for(i=0; i<Student::get_stu_num(); ++i)        {            if(stud[i].get_total()>=total_avg&&stud[i].pass())            {                outfile<<stud[i]<<endl;            }        }        outfile.close();        cout<<"请到pass_score.dat文件中查看总分高于平均总分且没有挂科的同学成绩"<<endl;        return 0;    }}


运算结果:

知识点总结:

使用文件保存数据,infile与outfile的再应用。

学习心得;

在新的学习过程中发现对过去知识的遗忘,需要加强复习!

0 0
原创粉丝点击