第14周 【项目2-用文件保存的学生名单】

来源:互联网 发布:孤岛危机1优化补丁 编辑:程序博客网 时间:2024/05/01 17:11

【项目2-用文件保存的学生名单】
文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。
(1)定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. //定义学生类  
  2. class Student{  
  3. public:  
  4.     //声明必要的成员函数  
  5. private:  
  6.     string name;  
  7.     double cpp;  
  8.     double math;  
  9.     double english;  
  10.     double total;  
  11.     static int stu_num;  //学生人数,处理为类的静态成员合适  
  12.     static double total_sum; //学生总分和  
  13. };  

(2)用对象数组进行存储学生的成绩,读入成绩并计算总分;将总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中。

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. int main( )  
  2. {  
  3.     Student stud[200],t; //stud[200]为保存数据的对象数组  
  4.     string sname;  
  5.     double total_avg;  
  6.     int i=0;  
  7.     //从文件score.dat中读入数据,保存到对象数组中  
  8.   
  9.   
  10.     //总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中  
  11.     return 0;  
  12. }  

讨论:学生人数和总分的另外一种解决方法是用全局变量。但这两种信息与学生有关,是学生类的“属性”,成为学生类的数据成员合适;这两种信息由学生整体决定,用作静态数据成员合适。如不理解这样设计的理由,复习课程前面的相关内容。

代码:

#include <iostream>#include <fstream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;class Student{public:    //声明必要的成员函数    Student(){};    ~Student(){    total_sum-=total;    stu_num--;    }    friend istream& operator>>(istream& in,Student& a);    friend ostream& operator<<(ostream& out,Student& a);    static int get_stu_num(){return stu_num;}    static double get_total_sum(){return total_sum;}    double get_total(){return total;}    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;istream &operator>>(istream& in,Student& a){    in>>a.name>>a.cpp>>a.math>>a.english;    a.total=a.cpp+a.math+a.english;    a.pass=(a.cpp>=60&&a.math>=60&&a.english>=60);    Student::stu_num++;    Student::total_sum+=a.total;    return in;}ostream &operator<<(ostream& out,Student& a){    out<<a.name<<"\t"    <<a.cpp<<"\t"    <<a.math<<"\t"    <<a.english<<"\t"    <<a.total<<'\12';}int main(){    Student stud[200],t; //stud[200]为保存数据的对象数组    string sname;    double total_avg;    int i=0;    //从文件score.dat中读入数据,保存到对象数组中    fstream myfile("score.dat",ios::in);    if(!myfile){        cerr<<"open error!\n";        exit(1);    }    while(!myfile.eof()){        myfile>>stud[i++];    }    myfile.close();    total_avg=Student::get_total_sum()/Student::get_stu_num();    ofstream outfile("pass.dat",ios::out);    if(!outfile){        cerr<<"open error!"<<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<<"运行完成请到相关文件查看!\n";    //总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中    return 0;}

运行结果:


0 0
原创粉丝点击