I am trying to write to a binary file , here is my snippet of code
#include
#include
#include
using namespac
You are storing the raw data of a struct
that, in fact, contains only pointers. That’s the way std::string
uses for storing data in order to make the string resizeable. The only reason your program does print any data is that in the moment of reading, the object person
still exists. If you put the reading part of your program into a separate program, you won’t be able to read any data.
To actually store your data using fstream
, you can store one string per line, for example:
afile << person.ID << endl;
afile << person.password << endl;
The file user.dat
:
001
abc
002
def
And you can read it this way:
afile >> person.ID >> person.password;
while (afile.good())
{
cout<> person.ID >> person.password;
}
You should also check Serializing a class which contains a std::string.