I am trying to write to a binary file , here is my snippet of code
#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;
}
}
I am expecting my console output to be
001 abc
002 def
Instead i am getting
002 def
002 def
Can someone explain to me?