第十四周

来源:互联网 发布:篮球鞋淘宝店 编辑:程序博客网 时间:2024/04/30 13:06
/*  * Copyright (c) 2014, 烟台大学计算机学院  * All rights reserved.  * 文件名称:test.cpp  * 作    者:张磊  * 版 本 号:v1.0  *  * 问题描述: (1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。 (2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。 (3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。 (4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 (5)用BinaryViewer命令查看二进制文件文件  * 程序输入:相应的程序 * 程序输出:对应得结果 */#include <iostream>#include <fstream>#include <cstring>#include <cstdlib>using namespace std;class Student{public:    Student() {}    Student(int n,string na,double c,double e,double m):num(n),name(na),cpp(c),english(e),math(m) {}    void get_value(int n,string na,int c,int e,int m);    string get_name()    {        return name;    }    double get_cpp()    {        return cpp;    }    double get_english()    {        return english;    }    double get_math()    {        return math;    }    double get_total()    {        return total;    }    void set_cpp(double p)    {        cpp=p;    }    double get_english(double e)    {        return english;    }    double get_math(double m)    {        return math;    }    double get_total(double t)    {        return total;    }    friend ostream& operator<<(ostream&out,Student&);private:    int num;    string name;    double cpp;    double english;    double math;    double total;};void Student::get_value(int n,string na,int c,int e,int m){    num=n;    name=na;    cpp=c;    english=e;    math=m;    total=c+e+m;}ostream& operator<<(ostream&out,Student&stu){    out<<stu.num<<" "<<stu.name<<" "<<stu.cpp<<" "<<stu.english<<" "<<stu.math<<" "<<stu.total<<endl;    return out;}int main(){    Student stud[100];    int i,n;    string sname;    double scpp,smath,senglish;    ifstream infile("score.dat",ios::in);    if(!infile)    {        cerr<<"open error"<<endl;        exit(1);    }    for(i=0; i<100; ++i)    {        infile>>n>>sname>>scpp>>smath>>senglish;        stud[i].get_value(n,sname,scpp,senglish,smath);    }    infile.close();    ofstream outfile("binary_score.dat",ios::out|ios::binary);//以二进制的形式写入数据    if(!outfile)    {        cerr<<"open error"<<endl;        exit(1);    }    for(i=0; i<100; ++i)    {        outfile.write((char*)&stud[i],sizeof(stud[i]));    }    //在最后写入自己的成绩    cout<<"输入自己的信息"<<endl;    cin>>n>>sname>>scpp>>senglish>>smath;    Student me(n,sname,scpp,senglish,smath);    outfile.write((char*)&me,sizeof(me));    outfile.close();    Student s;    ifstream infile2("binary_score.dat",ios::in|ios::binary);    if(!infile2)    {        cerr<<"open error!"<<endl;        exit(1);    }    while(true)    {        infile2.read((char*)&s, sizeof(s));        if(infile2.eof()) break;        cout<<s;    }    infile2.close();    return 0;}


 

0 0