I’m having some problems with displaying my file content correctly .
I have a program that writes an object with two member items, in binary mode, to my “person.dat” file.
Code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
class person
{
protected:
char name[80];
short age;
public:
void getData()
{
cout << "Enter name: "; cin >> name;
cout << "Enter age: "; cin >> age;
}
};
int main()
{
person pers;
pers.getData();
ofstream outfile ("person.dat", ios::binary);
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
cout << "finished" << endl;
system("PAUSE");
return 0;
}
Output
Enter name: Chad
Enter age: 24
finished
When I use another program to read this information I get very weird results.
Code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
class person
{
protected:
char name[80];
short age;
public:
void showData()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main()
{
person pers;
//pers.getData();
ifstream infile ("person.dat", ios::binary);
infile.read(reinterpret_cast<char*>(&pers), sizeof(pers));
pers.showData();
cout << "finished" << endl;
system("PAUSE");
return 0;
}
Output
Name: Hô|-wx;”
Age -96
finished
I use DevC++ to compile my sources if that helps any
NOTE: This is not a homework problem. The source code can be found in “Object-Oriented Programming in C++”, Robert Lafore, Page 592.