-1

I'm trying to write a vector that consists of a class called "Planet" to a file and have the program read the file when the program is ran. This is so that the Planets data will persist every time you run the program. I am using fstream.

This is my class declaration:

class Planet
{
    private:
        string name;
        double mass, diameter;

    public:
        double SurfaceArea();
        double Density();
        double Acceleration();
        void Input();
        void Display();

        void SetName(string s);
        bool SetMass(double x);
        bool SetDiameter(double x);
    
        string GetName();
        double GetMass();
        double GetDiameter();
    
        Planet();
        Planet(double m, double d);

};

This is how I am attempting to open the file called "data"

fstream file;
file.open("data", ios::app);

This is how I am attempting to write to the data file

for (int i=0; i<listOfPlanets.size();i++)
{
    file << listOfPlanets[i] << endl;
}
    
file.close();

Here is my declaration of listOfPlanets vector <Planet> listOfPlanets;

I am getting an error regarding a matching operator. Here it is pasted:

error: no match for ‘operator<<’ (operand types are ‘std::fstream’ {aka ‘std::basic_fstream<char>’} and ‘__gnu_cxx::__alloc_traits<std::allocator<Planet>, Planet>::value_type’ {aka ‘Planet’})
  297 |   file << listOfPlanets[i] << endl;

Just to clarify, I already have code written to add a Planet to the listOfPlanets vector, I just don't know how to write the planets to the data file and have the program read them when it runs again.

Note: I have included iostream and fstream in the code

If someone could help me out, that would be great. I think it may require some kind of loop, but I'm not sure. Thank you.

This is my first question here, so I apologize for any formatting issues.

script0
  • 387
  • 2
  • 12
kzina
  • 1
  • 1

1 Answers1

0

you are trying to save the values of class members incorrectly, you cannot use the << operator like this, because by not doing so you are trying to pass the whole class to the file object, when instead you have to pass the values of its members (for example for the name use GetName() to write the string to the file and so on)

for (int i=0; i<listOfPlanets.size();i++)
{
     file << listOfPlanets[i].GetName() << endl;
}

If you want to use the << operator and write all the values to file at once you need to overload the << operator

Carcons
  • 26
  • 3