gpt4 book ai didi

c++ - 从文件创建类

转载 作者:行者123 更新时间:2023-11-28 03:06:49 25 4
gpt4 key购买 nike

我不太明白为什么我的程序会打印出奇怪的数字,我认为这是地址数字……我正在尝试从文件中读取数据,然后将它们存储在类实例中……文件在一行中包含 id、x、y、z……它有 10 行,因此我必须创建 10 个类实例……很高兴得到您的帮助……^^

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

最佳答案

如果您为 the_planets 使用正确的索引,您的代码将有效

 report_planet_properties(*the_planets[i]);

在上面的行中,您必须使用循环变量 j 而不是 i,后者是文件中行星的数量。

 report_planet_properties(*the_planets[j]);

关于c++ - 从文件创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com