0

So i written a program where i can input 4 values a first name, last name, height and a signature. I store all values in a Vector but now i would like to learn how i can take the values from my vector and store them in a file and later on read from the file and store back into the vector.

vector<Data> dataVector;
struct Data info;
info.fname = "Testname";
info.lname = "Johnson";
info.signature = "test123";
info.height = 1.80;
dataVector.push_back(info);

Code looks like this i havent found anyway to store objects of a struct into a file so i'm asking the community for some help.

1
  • 1
    Store/load the members one by one for each struct in the vector. Commented Nov 13, 2015 at 18:10

2 Answers 2

2

You should provide your struct with a method to write it to a stream:

struct Data
{
    // various things
    void write_to(ostream& output)
    {
        output << fname << "\n";
        output << lname << "\n";
        // and others
    }
    void read_from(istream& input)
    {
        input >> info.fname;
        input >> info.lname;
        // and others
    }
};

Or provide two freestanding functions to do the job, like this:

ostream& write(ostream& output, const Data& data)
{
    //like above
}
// and also read

Or, better, overload the << and >> operator:

ostream& operator<<(const Data& data)
{
    //like above
}
// you also have to overload >>

Or, even better, use an existing library, like Boost, that provides such functionality.

The last option has many pros: you don't have to think how to separate the fields of the struct in the file, how to save more instances in the same file, you have to do less work when refactoring or modifying the struct.

Sign up to request clarification or add additional context in comments.

Comments

1

Don't reinvent the wheel: use the Boost serialization libraries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.