第一个:这样写读出结果会对,但是有时候也会出错。换成中文的有时也会出错。
#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;
}