I am trying to do some exercises but am struggling at the moment. The first task was to create a class (Planet), then allow the user to edit their entry or view it.
The second one is to create class instances from a text file. The file contains a new planet on each line in the form: 'id x y z' where x/y/z are its coordinates. As the file can have more then one lines, it has to dynamically create an undefined amount of class instances.
To do this I used 'new' and it works ok - it prints each one out to the screen as you go so you can see it working. However... I'm trying to get into good habits here and am encapsulating the class which is where I am getting stuck. I can read from the class but cannot put the values from the file into the class.. ..using the member functions I have created anyway.
Any help would be great

My code so far is:
#include <iostream> #include <fstream> #include <string> using namespace std; class Planet { private: int id=0; float x_coord=0.0, y_coord=0.0, z_coord=0.0; public: int GetID(){return id;} float GetX(){return x_coord;} float GetY(){return y_coord;} float GetZ(){return z_coord;} void SetID(int identity){id=identity;} void SetX(float x){x_coord=x;} void SetY(float y){y_coord=y;} void SetZ(float z){z_coord=z;} }; void set_planet_properties (Planet& pone); void report_planet_properties (Planet& pone); Planet* generate_planet (ifstream& planetlist) { Planet* p = new Planet; cout << "\n" << endl; string line; while ( getline (planetlist,line) ) { planetlist >> p->SetID() >> p->SetX() >> p->SetY() >> p->SetZ(); cout << "Planet ID (" << p->GetID() << ") has landing site coordinates: ( " << p->GetX() << " , " << p->GetY() << " , " << p->GetZ() << " )" << endl; } return (p); } int main() { int choice,tempid; float tempx,tempy,tempz; Planet pone; ifstream planetlist ("planets.txt"); generate_planet(planetlist); return 0; }
If I change the SetID etc to just p->id, p->x_coord etc it works fine. But I'd rather find a way to do it that keeps the encapsulation. Using p->z_coord etc requires that you change the class variables from private to public.
The question I have been given is this:
Define and implement a function, generate planet, that takes a stream argument that has already been connected to a file (i.e. the argument is istream& fin). The function must create a new instance of planet using new and read its details from the next line in the file. Each line of the file is in the format id x y z. The function must return the newly created planet.- encase you notice something or I'm misunderstanding the wording!
Also, how would you go about 'viewing' one specific class instance once they've been created? So say the file had 5 lines, line three was '4 6 2 6'. How would I go about viewing that planet afterwards? I don't think thats required but... I'm just wondering

Thanks!