因此,我正在尝试让我的程序从文本文件中读取结构数组,并且可以编译,但是似乎没有真正在读取值?。我不知道为什么。这是代码的相关部分:
typedef struct Planet
{
char Planet_Name[30];
double Fuel;
double Velocity;
double Height;
double Gravity;
int Maximum_Thrust;
double Difficulty;
}Planet;
//read the Planets from a file
FILE* inputFile = fopen("Planets.txt", "r");
if(inputFile == NULL)
{
perror("Error. File unavailable");
exit(1);
}
for(j=0; j<10; j++)
{
fscanf("%29s %lf %lf %lf %lf %d %lf", SolarSystem[j].Planet_Name,
SolarSystem[j].Fuel, SolarSystem[j].Velocity,
SolarSystem[j].Height, SolarSystem[j].Gravity,
SolarSystem[j].Maximum_Thrust, SolarSystem[j].Difficulty);
}
printf("Please select a planet by entering the corresponding number:
Mercury[0], Venus[1], Earth[2], Moon[3], Mars[4], Jupiter[5], Saturn[6],
Uranus[7], Neptune[8]\n");
scanf("%d",&PlanetNum);
printf("You have chosen %s", SolarSystem[PlanetNum].Planet_Name);
这是TXT文件(名称:Planets.txt)
汞120 50 500 12.1 30 2
金星120 50 500 29.1 30 6
地球120 50 500 32.2 30 7
月亮120 15 50 5.3 30 2
火星120 50 500 12.2 30 4
木星120 50 500 81.3 30 10
土星120 50 500 34.3 30 8
天王星120 50 500 28.5 30 5
海王星120 50 500 36.6 30 9
冥王星120 50 500 2.03 30 1
除了当它运行的是最后的printf,它实际上并没有显示任何信息,也没有任何数据存储在结构(其调用时以后是全零)。
有想法吗?
最佳答案
错误在于您的fscanf
函数。您必须在扫描整数和浮点数之前提供FILE pointer
(inputFile
此上下文)作为第一个参数,并提供&
运算符(类似于scanf
函数的地址)。
试试这个修改后的fscanf
代码:-
fscanf(inputFile,"%s%lf%lf%lf%lf%d%lf",SolarSystem[j].Planet_Name,&SolarSystem[j].Fuel, &SolarSystem[j].Velocity, &SolarSystem[j].Height, &SolarSystem[j].Gravity,&SolarSystem[j].Maximum_Thrust, &SolarSystem[j].Difficulty);
关于c - 从txt文件读入数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50512869/