chenerzhu 2015-03-17 14:05 采纳率: 50%
浏览 2804

关于C++文件的读写read和write问题!

第一个:这样写读出结果会对,但是有时候也会出错。换成中文的有时也会出错。
#include
#include
#include

using namespace std;

class People
{
private:
struct
{
string name;
string weight;
string tall;
string sex;
}people;
public:
People(){}
People(string name, string weight, string tall, string sex)
{
people.name=name;
people.weight=weight;
people.tall=tall;
people.sex=sex;
}
string get_Name()
{
return people.name;
}
string get_Sex()
{
return people.sex;
}
};

int main()
{
fstream file;
file.open("people.txt",ios::out|ios::binary);
People pe("aaa","bbb","ccc","sda");
People pe2;
file.write(reinterpret_cast(&pe),sizeof(pe));
file.close();
file.open("people.txt",ios::in|ios::binary);
file.read(reinterpret_cast(&pe2),sizeof(pe2));
cout<<pe2.get_Sex()<<" "<<pe2.get_Name();
file.close();
return 0;
}

第二种:是第一种写的文件读出来,为什么就会出错?
#include
#include
#include

using namespace std;

class People
{
private:
struct
{
string name;
string weight;
string tall;
string sex;
}people;
public:
People(){}
People(string name, string weight, string tall, string sex)
{
people.name=name;
people.weight=weight;
people.tall=tall;
people.sex=sex;
}
string get_Name()
{
return people.name;
}
string get_Sex()
{
return people.sex;
}
};

int main()
{
fstream file;
People pe2;
file.open("people.txt",ios::in|ios::binary);
file.read(reinterpret_cast(&pe2),sizeof(pe2));
cout<<pe2.get_Sex()<<" "<<pe2.get_Name();
file.close();
return 0;
}

  • 写回答

2条回答 默认 最新

  • oyljerry 2015-03-17 16:30
    关注

    string是动态类型,你sizeof方式求大小会有问题,造成数据读取不对。
    结构体要用基本数据类型。

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料