用二进制文件处理学生成绩】

问题描述:

【项目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;}运行结果:

接受我们不能改变的一切,改变我们能改变的一切。

用二进制文件处理学生成绩】

相关文章:

你感兴趣的文章:

标签云: