0

i am new to c++ and i'm try to write a code that reads integers of a text file and saves each integer in different variables line by line. I am having problems with the syntax and how to arrange the code. Basically the text file contains 4 integers per line which values are to be read to the a class planet's coordinates and id as shown below. I know the code beloe is incomplete but this is the first time im programming with c++ and need help. please you do not need to explain this using planets or anything. I just need a general understanding

#include <iostream>
#include <fstream>



using namespace std;

class planet{
    public :
    float x_coordinates;
    float y_coordinates;
    float z_coordinates;
    int id;
};




planet*generate_planet(istream &fin)
{
    planet *x= new planet;
    fin >> x->id >> x->x_coordinates >> x->y_coordinates >> x->z_coordinates;

    return (x);
}
void report_planet( planet &p)
{

 cout<<"planet "<<p.id<<" has coordinates (" << p.x_coordinates<<","<<       p.y_coordinates<<","<< p.z_coordinates<<")"<<endl;
}
int main()
{
planet p;
planet *x;
ifstream fin("route.txt");
generate_planet(fin);
report_planet(*x);


  return 0;
}
Tobey
  • 1,400
  • 1
  • 10
  • 25
  • Some issues: you don't save the returned planet* from generate_planet to pass to report_planet(). You leak this memory. Then you pass an ofstream to report_planet() instead of whatever generate_planet() returns. – Mike Corcoran Oct 25 '12 at 12:50

1 Answers1

3

You have some errors in your code.

Note that in this line: fin>>x->id>>x->x_coordinates>>x->y_coordinates>>x->y_coordinates; You write twice to x->y_coordinate instead of x->z_coordinate.

Also, your void report_planet(planet &p) function receives planet & as argument, but you pass it fin which is of time ofstream

Another thing is you're trying to read a file, not write to one, hence the use of ofstream is wrong, you should use ifstream instead.

Does your code even compile?

Good luck.

La bla bla
  • 8,558
  • 13
  • 60
  • 109
  • thanks for the observations, It compiled but its not running properly, i will add the corrections u stated – Tobey Oct 25 '12 at 12:56
  • there are some more errors and design issues in here. You should delete everything you created with new.Also i suggest that "create_planet" should be a constructor type for your planet class and "report_planaet" a member function. Please look at some basics of object orientation in C++. Classes are no structs. – TWE Oct 25 '12 at 13:41
  • Also, if this answer helped you, please consider an up-vote accepting it. – La bla bla Oct 25 '12 at 21:08