dknight dknight - 27 days ago 5
C++ Question

Why does the data written in a file using a class object in C++ get stored in a non-text format?

I was using c++ to write data to a file. When I use simply a variable to take input from the user and then to write in file, it gets simply stored in that file. I mean I can read what my input was by opening the file with notepad. But when I define a class and use its object to write data to file, it gets stored in an unreadable format. I can't read what my input was just by opening the file with notepad. However, in both cases, when I read the files using c++ and then display them, they both show what I had entered. So, I want to ask, why is data getting stored in some other format while using classes but not when using simple variables.

Using normal variables:

#include <fstream>
#include <iostream>
using namespace std;

int main () {

//char data[100];
string data;
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin>>data;
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}


Data in the file:

Ram
14


Using Class:

#include <bits/stdc++.h>
using namespace std;

class person{
public:
int age;
string name;

int retAge(){
return age;
}
string retName(){
return name;
}
void takeInput(){
cout<<"\nEnter Age: ";
cin>>age;
cout<<"\nEnter Name: ";
cin>>name;
}
void show(){
cout<<"\nAge: "<<age<<" and Name: "<<name;
}
};

int main(){
string filename = "someFile.dat";
ofstream outfile;
outfile.open (filename.c_str(), ios::app);
person p, q;
p.takeInput();
p.show();
outfile.write ((char *)(&p), sizeof(p));
outfile.close();
ifstream infile;
infile.open(filename.c_str());
infile.read((char*)&q, sizeof(q));
infile.close();
q.show();
return 0;
}


Data in the file:

 ”Xã

Answer Source

You are writing the address of a person, cast to a char *: outfile.write ((char *)(&p), sizeof(p));. It will not magically be converted to a readable string showing all the content of the object; you need to do that yourself.

Right now, the address of the person is a pointer into the memory, something like 0x42f1a5e2, and that's what you write in the file. Reading it back as string gives you some random characters.

For example, the age is an int, so you need to convert it to a string and write that string, and so on for all fields.