c++二进制文件无法读取正常
include
#include
#include
#include
using namespace std;
class Student{
public:
Student(){
}
Student(int id,char n[],double cpp,double math,double english){
this->id=id;
strcpy(name,n);
this->cpp=cpp;
this->math=math;
this->english=english;
sum=cpp+math+english;
}
double set(int id,char n[],double cpp,double math,double english){
this->id=id;
strcpy(name,n);
this->cpp=cpp;
this->math=math;
this->english=english;
sum=cpp+math+english;
}
int get_id(){
return id;
}
double get_cpp(){
return cpp;
}
double get_math(){
return math;
}
double get_english(){
return english;
}
double get_sum(){
return sum;
}
int id;
char name[100];
double cpp;
double math;
double english;
double sum;
};
int main(){
Student num[101];
int Id;
double English,Math,Cpp;
char Name[100];
char n[100];
fstream f1;
f1.open("score.dat",ios::in);
if(f1.fail()){
cout<<"打开文件失败!"<<endl;
exit(1);
}
for(int i=0;i<100;i++){
f1>>Id>>Name>>Cpp>>Math>>English;
num[i].set(Id,Name,Cpp,Math,English);
}
f1.close();
fstream f2;
f2.open("binary_score.dat",ios::out|ios::binary);
if(f2.fail()){
cout<<"打开文件失败!"<<endl;
exit(2);
}
for(int i=0;i<100;i++){
f2.write((char*)&num[i],sizeof(num[i]));
}
cout<<"请输入信息:"<<endl;
cin>>Id>>Name>>Cpp>>Math>>English;
Student s(Id,Name,Cpp,Math,English);
f2.write((char*)&s,sizeof(s));
f2.close();
Student x;
fstream f3;
f3.open("binary_score.dat",ios::in|ios::binary);
if(f3.fail()){
cout<<"打开文件失败!"<<endl;
exit(3);
}
while(!f3.eof()){
f3.read((char*)&x,sizeof(x));
cout<<x.get_id()<<" "<<x.name<<" "<<x.get_cpp()<<" "<<x.get_math()<<" "<<x.get_english()<<" "<<x.get_sum()<<endl;
}
f3.close();
return 0;
}