您的位置:首页 > 其它

第十六周实践项目4————用二进制文件处理学生信息

2016-06-16 09:14 435 查看
问题及代码:

#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),english(e){total=c+m+e;}
void set_value(int n,string nam, double c, double m, double e);
friend  ostream& operator<<(ostream&, Student&);

private:
int num;
string name;
double cpp;
double math;
double english;
double total;
};
void Student::set_value(int n,string nam, double c, double m, double e)
{
num=n;
name=nam;
cpp=c;
math=m;
english=e;
total=c+m+e;
}

ostream& operator<<(ostream& out, Student& s)
{
out<<s.num<<" "<<s.name<<" "<<s.cpp<<" "<<s.math<<" "<<s.english<<" "<<s.total<<endl;
return out;
}
int main()
{
Student stu[100];
int i,n;
string sname;
double scpp,smath,senglish;
ifstream infile("score.txt",ios::in);
if(!infile)
{
cerr<<"open error"<<endl;
exit(1);
}
for(i=0;i<100;i++)
{
infile>>n>>sname>>scpp>>smath>>senglish;
stu[i].set_value(n,sname,scpp,smath,senglish);
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*)&stu[i],sizeof(stu[i]));
}
cout<<"输入你自己的信息"<<endl;
cin>>sname>>scpp>>smath>>senglish;
Student me(n,sname,scpp,smath,senglish);
outfile.write((char *)&me,sizeof(me));
outfile.close();
Student s;
ifstream infile2("binary_score.dat",ios::in|ios::binary);
if(!infile)
{
cerr<<"open error"<<endl;
exit(1);
}
while(true)
{
infile2.read((char*)&s,sizeof(s));
if(infile2.eof())
{
break;
}
cout<<s;
}
infile2.close();
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: