The below code saves data in a file using the member function save() and reads data back using the static function load().
Loading data using load() function is successfull but using dump() function to print the result gives unexpected result, link for the image is provided for reference(https://i.stack.imgur.com/67qgH.jpg).
Accessing the members of class from main() gives right result.
Could anyone please find out what is wrong in my code.
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
int ID;
char name[20];
Person() { ID = -1; memset(name, '\0', 20); }
void get_data();
void dump();
bool save();
static Person *load(int id);
};
void Person::get_data() {
cout << "Enter ID: ";
cin >> ID;
cout << "Enter name: ";
cin.ignore();
cin.get(name, 20);
}
void Person::dump() {
cout << "ID : " << this->ID << endl;
cout << "Name: " << this->name << endl;
}
bool Person::save() {
ofstream outfile("person.dat", ios::app | ios::binary);
if(!outfile) { return false; }
outfile.write((char*)this, sizeof(Person));
outfile.close();
return true;
}
Person *Person::load(int id) {
Person tmp, *p;
ifstream infile("person.dat", ios::binary);
if(!infile) { return NULL; }
while(true) {
infile.read((char*)&tmp, sizeof(Person));
if( infile.eof() ) break;
if(tmp.ID == id) {
infile.close();
p = &tmp;
return p;
}
}
infile.close();
return NULL;
}
int main(int argc, char *argv[]) {
if(argc == 1) { // if statement to save data to file
Person p;
p.get_data(); // get user input[enter image description here][1]
if( p.save() ) cout << "Save successfull\n"; // save data
else cout << "Save aborted\n";
}
else { // if statement to load data from file
Person *p;
int id;
cout << "Enter person ID to search: ";
cin >> id;
p = Person::load(id); // load data
if( !p ) {
cout << "Person not found\n";
} else {
printf("%d, %s\n", p->ID, p->name); // gives right result
p->dump(); // gives wrong result
}
}
return 0;
}
[1]: