我正在尝试写入二进制文件,这是我的代码片段:
我期望我的控制台输出为:
我得到的是:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct user
{
string ID;
string password;
};
int main()
{
fstream afile;
afile.open("user.dat",ios::out|ios::binary);
user person;
person.ID ="001";
person.password ="abc";
afile.write (reinterpret_cast <const char *>(&person), sizeof (person));
person.ID ="002";
person.password ="def";
afile.write (reinterpret_cast <const char *>(&person), sizeof (person));
afile.close();
afile.open("user.dat",ios::in|ios::binary);
while (afile.read (reinterpret_cast <char *>(&person), sizeof (person)))
{
cout<<person.ID
<<" "
<<person.password
<<endl;
}
}
我期望我的控制台输出为:
001 abc
002 def
我得到的是:
相反我得到了
002 def
002 def
有人能向我解释一下吗?
afile
一样关闭它总是一个好主意。 - Jonny Henlystd::string
不是一个普通的数据对象,你不能以这种方式将它们转储到/从文件中读取。请考虑使用 __序列化__。 - Blastfurnacestd::string
内部有一个指针,您正在写入和读取该指针,而不是字符串本身。 - chris