jeudi 28 mars 2019

How to save an object with string variables to a binary file in C++?

I'm working on a project for my programming class, and I have to save an object to a file in binary format. The problem I'm facing is that the object has string variables in it. When I write the object to the file and read the data into another object, the receiving object gets the correct strings, but closing the program and rerunning it and rereading the data into the object shows that the strings are not correctly read.

I tried writing the size of the object in the binary file before writing the object to the file, but no matter how big the strings are, the size of the object stays the same.

The object:

class Song
{
    unsigned int file_size;
    string artist,
           song_name;

public:
    //input song data
    void input()
    {
        cout << "Artist: ";
        cin >> artist;
        cout << "Song: ";
        cin >> song_name;
        cout << "File size: ";
        cin >> file_size;
    }
};

The reading and writing:

Song x, y;
unsigned int file_size_x;

x.input( );  //input song data

file_size_x = sizeof(x);

//write size of song object, and the song object
file.write(reinterpret_cast<char *>(&file_size_x), sizeof(file_size_x));
file.write(reinterpret_cast<char *>(&x), sizeof(x));

//read size of song object, and put song data into another song object
file.seekg(0, ios::beg);
file.read(reinterpret_cast<char *>(&file_size_x), sizeof(file_size_x));
file.read(reinterpret_cast<char *>(&y), file_size_x);
y.print( );

Results before closing program:

Enter the artist: TestArtist
Enter the song: TestSong
Enter the file size: 2

TestArtist, TestSong, 2

Results after reopening program (no input, just rereading data from file):

 @ Ç@   ,   m  ╩çv, 2

Aucun commentaire:

Enregistrer un commentaire