class test{
int x;
public:
//public functions getx() and putx()
};
void main()
{
fstream file;
test ob;
file.open("test.txt",ios::in|ios::out);
file.write((char *)&ob,sizeof(ob));
file.close();
}
When this code is executed, suppose the value of x in the current object is assigned as 1 using getx() function, the character corresponding to ascii value 1 gets stored in the text file, instead of the numeric 1. how to solve this?
Are you assigning x with getx()? I would expect putx(int x) to be used for assignment. In any case, you can write int to file using
Or, like @Oli Charleswoth said, write a serialization function that does this inside your class.
Similar to your question: Writing multiple variable types to a text file using ofstream