Tobey
Tobey

Reputation: 1440

Reading text files c++

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;
}

Upvotes: 0

Views: 475

Answers (1)

La bla bla
La bla bla

Reputation: 8718

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.

Upvotes: 3

Related Questions