2015年大一下第14周项目1-用二进制文件处理学生成绩

来源:互联网 发布:淘宝买家退货卖家拒收 编辑:程序博客网 时间:2024/06/05 06:54
/* *Copyright (c) 2014,烟台大学计算机学院 *All rights reserved. *文件名称:Annpion.cpp *作者:王耀鹏 *完成日期:2015年6月17日 *版本号:v1.0 * *问题描述:用二进制文件处理学生成绩.*输入描述: 自己的信息*输出描述:输出由文件读入的学生信息和自己的信息。*/ #include <iostream>#include <fstream>#include <cstdlib>using namespace std;class Student{public:    void setdata(int n,string nam,double c,double m,double e);    friend ostream &operator <<(ostream &output,Student &s);private:    int num;    string name;    double cpp;    double math;    double english;    double total;};void Student::setdata(int n,string nam,double c,double m,double e){    num=n;    name=nam;    cpp=c;    math=m;    english=e;    total=cpp+math+english;}ostream &operator <<(ostream &output,Student &s){    output<<s.num<<'\t'<<s.name<<'\t'<<s.cpp<<'\t'<<s.math<<'\t'<<s.english<<'\t'<<s.total;    return output;}int main(){    int n;    string nam;    double c,m,e;    int i=0;    Student stu[100];    ifstream infile("score.dat");    if(!infile)    {        cerr<<"can't open the file of score.dat!"<<endl;        exit(1);    }    for(i=0; i<100; ++i)    {        infile>>n>>nam>>c>>m>>e;        stu[i].setdata(n,nam,c,m,e);    }    infile.close();    ofstream outfile("binary_score.dat",ios::binary);    if(!outfile)    {        cerr<<"can't open the file of binary_score.dat!"<<endl;        exit(1);    }    outfile.write((char *)&stu[0],sizeof(stu));    Student me;    cout<<"请输入自己的信息:";    cin>>n>>nam>>c>>m>>e;    me.setdata(n,nam,c,m,e);    outfile.write((char *)&me,sizeof(me));    outfile.close();    ifstream infile2("binary_score.dat",ios::binary);    if(!infile)    {        cerr<<"can't open the file of binary_score.dat!"<<endl;        exit(1);    }    infile2.read((char *)&stu[0],sizeof(stu));    for(int j=0; j<100; ++j)        cout<<stu[j]<<endl;    infile2.close();    cout<<me<<endl;    return 0;}


运行结果:

0 0
原创粉丝点击