0

When I input data into a text file using a class object, the text file shows some weird text instead of the data I entered. I entered "Flash" and 100 but the text file shows some weird text.link to snap of text file . Any help?

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

class Details
{
        string name;
        int roll;
    public:
        void get();
};
void Details::get()
{
    cout<<"Enter name : ";
    cin>>name;
    cout<<"Enter Roll No. : ";
    cin>>roll;  
}  

int main()
{
    Details obj;
    ofstream fout;
    fout.open("newdetails.txt",ios::app);
    obj.get();
    fout.write((char *)&obj,sizeof(obj));
    fout.close();
    return 0;
}
Shivam Negi
  • 373
  • 5
  • 9

1 Answers1

0

You're writing the file in binary format - it won't produce human-readable text in a normal text editor.

To write the file in a human-readable text format, use something like:

fout << obj.name << ' ' << obj.roll << '\n';

I answered a very similar question an hour ago - read that question and my answer to learn more about this here.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Didn't know that 'write' method does it in binary format. Thanks. Does the 'read' method read in binary format too? – Shivam Negi Apr 21 '18 at 17:01
  • @ShivamNegi: yes, that's right, though do note that using `read` and `write` is orthogonal to having opened the file in binary mode, which inhibits newline/carriage-return related translations done in text mode. That's touched on in my linked answer, or you can find other answers - e.g. [here](https://stackoverflow.com/a/20864389/410767). – Tony Delroy Apr 21 '18 at 23:42