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

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日

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因