Reputation: 137
I dont quite get the reason why my program prints out weird numbers which I believe it's the address numbers....I'm trying to read the data from a file and then store them in class instances....the file has the id,x,y,z in a line....it has 10 lines, hence i gotta create 10 class instances..would be glad for your help...^^
class planet
{
public:
int id_planet;
float x,y,z;
};
void report_planet_properties(planet& P)
{
cout<<"Planet's ID: "<<P.id_planet<<endl;
cout<<"Planet's coordinates (x,y,z): ("<<P.x<<","<<P.y<<","<<P.z<<")"<<endl;
}
planet* generate_planet(ifstream& fin)
{
planet* p = new planet;
fin >> (*p).id_planet;
fin >> (*p).x;
fin >> (*p).y;
fin >> (*p).z;
return (p);
}
int main()
{
planet* the_planets[10];
int i=0;
ifstream f_inn ("route.txt");
if (f_inn.is_open())
{
f_inn >> i;
for(int j=0;j<i;j++)
{
the_planets[j]=generate_planet(f_inn);
report_planet_properties(*the_planets[i]);
delete the_planets[j];
}
f_inn.close();
}
else cout << "Unable to open file";
}
Upvotes: 0
Views: 83
Reputation: 17595
Your code would work if you use the right index for the_planets
report_planet_properties(*the_planets[i]);
In the above line you have to use your loop variable j
not i
which is the number of planets in your file.
report_planet_properties(*the_planets[j]);
Upvotes: 1
Reputation: 1817
I don't understand some parts of your code (e.g. why you create new instances of planet inside generate_planet) but I am not an experienced C++ programmer. However, I modified your code and found this one to work:
#include <iostream>
#include <fstream>
using namespace std;
class planet
{
private:
int id_planet;
float x,y,z;
public:
void generate_planet(ifstream& fin);
void report_planet_properties();
};
void planet::report_planet_properties() {
cout << "\nPlanet's ID: " << id_planet << endl;
cout << "\nPlanet's coordinates (x,y,z): ("<< x <<","<< y <<","<< z<<")"<<endl;
}
void planet::generate_planet(ifstream& fin) {
fin >> id_planet;
fin >> x;
fin >> y;
fin >> z;
}
int main() {
planet the_planets[10];
int i=0;
ifstream f_inn("route.txt");
if (f_inn.is_open())
{
f_inn >> i;
for(int j=0;j<i;j++)
{
the_planets[j].generate_planet(f_inn);
the_planets[j].report_planet_properties();
}
f_inn.close();
}
else cout << "Unable to open file\n";
return 0;
}
with route.txt:
2
1
4
5
6
2
7
8
9
gives:
Planet's ID: 1
Planet's coordinates (x,y,z): (4,5,6)
Planet's ID: 2
Planet's coordinates (x,y,z): (7,8,9)
As you can see the functions generate_planet() and report_planet_properties() are now methods of the planet class.
Maybe this can help you.
Upvotes: 1