views:

203

answers:

5
+2  A: 

Is the name string in the Person struct a character array or a STL string? You can't fill in an STL String by binary reading data over top of it, since the data format is not serializable (contains pointers)

bdk
A: 

Either p2.name is a char* and you are writing and reading the pointer value, not what is pointed by it. Or p2.name is a more complex type such as std::string which is using internaly pointers with the same problem.

Serializing classes often need more work than just dumping the memory representation.

AProgrammer
but if it's char name[100], that would probably work.
sharth
A: 

You said you wrote the Person object to a file. Did you tried to use a dump tool to see if what you have inside the file is what you are expecting?

Also did you tried to instead of using string, use a ordinary char (as @bdk pointed out) ?

Andres
+1  A: 

It would be interesting to see how you write the information to file as well, as well as how the Person struct is built.
If you don't have any problem that the file is plain text, my suggestion would be to write to file using string::c_str() (which returns a const char*) as well as using itoa() or itoa_s() to get the integer as a char*.

You can also have one or several constructors in Person:

Person(const std::string& name, int age);  
Person(const char* name, int age);

then, when you extract the data from the file you just call the constructor with that data.

Default
A: 

When you use binary IO, the size must be fixed. If you use STL string here, it would have a problem as the size of a STL string is arbitrary.

Foxcat