15周【项目1-用二进制文件处理学生成绩】

问题描述:

【项目1-用二进制文件处理学生成绩】 
(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。 
(2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。 
(3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。 
(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 
(5)用BinaryViewer命令查看二进制文件文件 

代码实现:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
class Student{
private:
    string name;
    double cpp,math,eng,total;
    int stu_id;
public:
    Student()=default;
    Student(string s,double c,double m,double e):name(s),cpp(c),math(m),eng(e){
        total=cpp+math+eng;
    }
    friend istream&operator>>(istream&in,Student& a);
    friend ostream&operator<<(ostream&out,Student& a);
};
istream&operator>>(istream&in,Student&a){
    in>>a.stu_id>>a.name>>a.cpp>>a.math>>a.eng;
    return in;
}
ostream&operator<<(ostream&out,Student& a){
    out<<"Student ID: "<<a.stu_id<<"\tName:"<<a.name<<"\tC++: "<<a.cpp<<"\tMath: "<<a.math
    <<"\tEnglish: "<<a.eng<<"\tTotal: "<<a.total;
    return out;
}
int main(){
    cout<<"请输入学生信息!\n";
    Student stud[101];
    int i;
    ifstream myfile("score.dat",ios::in);
    if(!myfile){
        cerr<<"open error!\n";
        exit(1);
    }
    for(i=0;i<100;i++){
        myfile>>stud[i];
    }
    cin>>stud[100];
    myfile.close();
    ofstream out("binary.dat",ios::out|ios::binary);
    if(!out){
        cerr<<"can't write the binary.dat file!\n";
        exit(1);
    }
    for(i=0;i<101;i++){
        out.write((char*)&stud[i], sizeof(stud[i]));
    }
    out.close();
    string s;
    ifstream oo("binary.dat",ios::in|ios::binary);
    if(!oo){
        cerr<<"can't write the binary.dat file!\n";
        exit(1);
    }
    oo.close();
    return 0;
}
运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值