(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 nam,double c,double m,double e):num(n),name(nam),cpp(c),math(m),eng(e) {}
friend ostream& operator <<(ostream&, Student&);
friend istream& operator >>(istream&, Student&);
private:
int num;
string name;
double cpp,math,eng;
double sum;
};
ostream& operator<<(ostream &out, Student&s)
{
out<<s.num<<'\t'<<s.name<<'\t'<<s.cpp<<'\t'<<s.math<<'\t'<<s.eng<<'\t'<<s.sum<<endl;
return out;
}
istream& operator>>(istream &in, Student &s)
{
in>>s.num>>s.name>>s.cpp>>s.math>>s.eng;
s.sum=s.cpp+s.math+s.eng;
return in;
}
int main()
{
Student stu[100],my_s;
ifstream infile("score.dat",ios::in);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0; i<100; ++i)
{
infile>>stu[i];
}
infile.close();
ofstream outfile("binary.dat",ios::out|ios::binary);
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0; i<100; ++i)
{
outfile.write((char*)&stu[i],sizeof(stu[i]));
}
cout<<"输入你的成绩:"<<endl;
cin>>my_s;
outfile.write((char*)&my_s,sizeof(my_s));
outfile.close();
ifstream infile1("binary.dat",ios::in|ios::binary);
if(!infile1)
{
cerr<<"open error!"<<endl;
exit(1);
}
Student st;
while(1)
{
infile1.read((char*)&st, sizeof(st));
if(infile1.eof()) break;
cout<<st;
}
infile1.close();
return 0;
}
图片:
心得:
在最后输出的时候,我用了如下结构:
while(!infile.eof())
{
infile1.read((char*)&st,sizeof(st));
cout<<st;
}
结果在程序的末尾会出现两次自己的成绩,参考了一下贺老的程序,好像是先读再判断可以防止到文件尾继续读?但是自己的成绩已经写进去了啊,只是输出的判断方法不同,So其实并不明白。。。