#include <fstream>
#include <iostream>
#include "player.h"
usingnamespace std;
int main(){
char dummy;
char choice;
Person person,saved_person;
ofstream output_file("C:/Users/Mike/Desktop/test/save.dat",ios::binary);
ifstream input_file("C:/Users/Mike/Desktop/test/save.txt",ios::binary);
cout<<"'1' to save\n"
<<"'2' to load\n"
<<":->";
cin>>choice;
if(choice=='1'){
person.get_data();
output_file.write(reinterpret_cast<char*>(&person),sizeof(person));
exit(1);
}
if(choice=='2'){
cout<<"The following information has been saved\n\n";
input_file.read(reinterpret_cast<char*>(&person),sizeof(person));
saved_person.show_data();
}
cin>>dummy;
return 0;
}
This is a simple example from and old Lafore C++ book, with a few tweaks by me. The point is simple. Save object person to a *.dat file, exit the program, then start up program again, open up *.dat file, and load contents.
The first problem is the compiler is printing a bunch of Asian characters to the file (is this normal?)
The second problem is, it's not loading the object as it should, giving me a bunch of gibberish.
Just, to get things straight, you're writing to save.dat, then changing its extension and reading from save.txt, correct?
Maybe the problem is that name is not null terminated. Try making a constructor for person and zeroing out name. i.e.
1 2 3 4
Person::Person()
{
memset(name, 0, sizeof(name)); //will work because name is an array
}
I did not try using a struct, as classes are so much more useful.
I was just saying that writing the whole class instance at once to a file is not guaranteed to work. You could for instance make WriteFile and LoadFile methods that save/load the members one at a time.
#include <fstream>
#include <iostream>
#include "player.h"
usingnamespace std;
int main(){
char dummy;
char choice;
Person person,saved_person;
ofstream output_file("C:/Users/Mike/Desktop/test/save.dat",ios::binary);
ifstream input_file("C:/Users/Mike/Desktop/test/save.dat",ios::binary);
cout<<"'1' to save\n"
<<"'2' to load\n"
<<":->";
cin>>choice;
if(choice=='1'){
person.get_data();
output_file.write(reinterpret_cast<char*>(&person),sizeof(person));
exit(1);
}
if(choice=='2'){
cout<<"The following information has been saved\n\n";
input_file.read(reinterpret_cast<char*>(&person),sizeof(person));
person.show_data();
}
cin>>dummy;
return 0;
}
This is more or less as it appears in the book. But I still get gibberish written to either *.dat file or *.txt. It does not matter which one I choose. And of course when I read it back in, it's nonsense.