m0_70323518 2022-05-15 16:43 采纳率: 100%
浏览 115
已结题

c++二进制文件无法读取string

#include
#include
#include
#include
using namespace std;

class Student{
public:
Student(){
}
Student(int id,string name,double cpp,double math,double english){
this->id=id;
this->name=name;
this->cpp=cpp;
this->math=math;
this->english=english;
sum=cpp+math+english;
}
double set(int id,string name,double cpp,double math,double english){
this->id=id;
this->name=name;
this->cpp=cpp;
this->math=math;
this->english=english;
sum=cpp+math+english;
}
int get_id(){
return id;
}
string get_name(){
return name;
}
double get_cpp(){
return cpp;
}
double get_math(){
return math;
}
double get_english(){
return english;
}
double get_sum(){
return sum;
}
private:
int id;
string name;
double cpp;
double math;
double english;
double sum;
};
int main(){
Student num[101];
int Id;
double English,Math,Cpp;
string Name;
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.get_name()<<" "<<x.get_cpp()<<" "<<x.get_math()<<" "<<x.get_english()<<" "<<x.get_sum()<<endl;
}
f3.close();
return 0;
}

img

  • 写回答

2条回答 默认 最新

  • 关注

    string是个复杂结构,是个container,

    它的数据不在你所见的string上,所以不能 sizeof(),如果想用二进制的存和读,用char[ 100 ],这个是有定长的。
    *
    否则你存的string大概是个 指针 + 2个unsigned int 而非字符串。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月24日
  • 已采纳回答 5月16日
  • 创建了问题 5月15日

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同