samedi 10 avril 2021

Saving Class Object to Binary File

I am looking for an easy way to save and load this C++ object to and from a binary file.

#include <iostream>
#include <vector>

class User
{
private:
    std::string _name;
    int _age;
    std::vector<std::string> _hobbies;
public:
    std::string Name() { return _name; }
    int Age() { return _age; }

    std::vector<std::string> Hobbies() { return _hobbies; }
    void Hobbies(std::string hobbieName)
    {
        _hobbies.push_back(hobbieName);
    }

    User(std::string name, int age)
    {
        _name = name;
        _age = age;
    }
};

int main()
{
    User u1 = User("John", 48);
    u1.Hobbies("Art");
    u1.Hobbies("Lego");
    u1.Hobbies("Blogging");

    User u2 = User("Jane", 37);
    u2.Hobbies("Walking");
    u2.Hobbies("Chess");
    u2.Hobbies("Card Games");

    std::cout << u1.Name() << "'s Hobbies:\n";
    for (std::string hobbie : u1.Hobbies())
    {
        std::cout << hobbie << "\n";
    }

    std::cout << u2.Name() << "'s Hobbies:\n";
    for (std::string hobbie : u2.Hobbies())
    {
        std::cout << hobbie << "\n";
    }

    //Save 'u1' to file.

    //Load 'u1' from file into a new 'User' object
}

I have looked at a number of StackOverflow answers for similar questions, but I am struggling to find a solution specifically regarding using the vector in my class. I would appreciate any suggestions that you might have.

Aucun commentaire:

Enregistrer un commentaire