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方式求大小会有问题,造成数据读取不对。
    结构体要用基本数据类型。

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型