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;"afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
outfile << data << endl;
ifstream infile;"afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
return 0;

Data in the file:


Using Class:

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

class person{
int age;
string name;

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

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

Data in the file:


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.