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.
OutputCode:#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; }
Enter name: Chad
Enter age: 24
finished
When I use another program to read this information I get very weird results.
OutputCode:#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; }
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.



LinkBack URL
About LinkBacks




See this FAQ entry about writing struct/class objects to a file: