отладка чтение / запись строки в двоичный файл
Я пытаюсь записать в двоичный файл, вот мой фрагмент кода
#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
Может кто-нибудь объяснить мне?