What is going on here is that you aren't formatting the output. All output must be formatted in some way, in order to ensure that you can reread it; just copying the bit pattern from memory is useless.
The usual way of handling this would be to define an operator
<<
(and an operator >>
, in order to read) for your class.
This operator will output all of the individual elements of the
class, with appropriate separators so that you can determine
where one ends and the next begins when you read. If, for
example, we take a simple example:
class Person
{
std::string name;
int age;
public:
// ...
friend std::ostream& operator<<( std::ostream& dest, Person const& obj )
{
dest << '"' << name << '"' << age;
return dest;
}
friend std::istream& operator>>( std::istream& source, Person& obj )
{
char ch;
source >> ch;
if ( ch != '"' ) {
source.setstate( std::ios_base::failbit );
}
std::string name;
while ( source.get( ch ) && ch != '"' ) {
name += ch;
}
if ( ch != '"' ) {
source.setstate( std::ios_base::failbit );
}
int age;
source >> age;
if ( source ) {
obj = Person( name, age );
}
return source;
}
};
You'll notice that input is a lot more difficult than output.
When outputting, you know what you've got (because of the C++
type system, and your own verification of class invariants).
When inputting, you never know what the user is going to give
you, so you have to check for all possibilities. (You might,
for example, want to forbid additional characters like
a '\n'
in the name. Just add them to the test in the
while
.)