C语言读取TXT到结构体数组失败:编译正常但无数据写入
问题分析:C语言结构体数组无法从文件读取数据
嘿,我一眼就发现几个核心问题,导致你的程序虽然能编译,但完全没从文件里读进数据。咱们一步步拆解解决:
最致命的错误:fscanf没指定文件指针
你现在写的fscanf("%29s %lf ...", ...),默认是从**标准输入(键盘)**读取数据,而不是你打开的inputFile文件!这就相当于你打开了文件,但根本没对着它读,自然结构体里全是空的。
必须把打开的文件指针作为fscanf的第一个参数:
fscanf(inputFile, "%29s %lf %lf %lf %lf %d %lf", ...);
第二个错误:double/int类型变量没传地址
fscanf需要通过地址来修改变量的值,对于char数组(比如Planet_Name),数组名本身就是指针,所以没问题,但double类型的Fuel、Velocity,以及int类型的Maximum_Thrust这些变量,必须传它们的地址(用&取地址符)。
比如你原来写的SolarSystem[j].Fuel,要改成&SolarSystem[j].Fuel,同理其他非字符数组的字段也要做同样修改。
其他需要注意的细节
- 关闭文件:读完数据后记得用
fclose(inputFile);,避免资源泄漏。 - 检查
fscanf返回值:每次调用fscanf可以检查它的返回值,判断是否成功读取了7个字段(你的结构体有7个数据项),方便调试读取失败的情况。 - 文件路径:确保
Planets.txt和你的可执行程序在同一目录下,或者使用绝对路径(比如Windows下写fopen("C:/Projects/Planets.txt", "r"),反斜杠要写两个\\)。
修正后的核心代码片段
typedef struct Planet { char Planet_Name[30]; double Fuel; double Velocity; double Height; double Gravity; int Maximum_Thrust; double Difficulty; } Planet; // 读取行星数据 FILE* inputFile = fopen("Planets.txt", "r"); if(inputFile == NULL) { perror("Error. File unavailable"); exit(1); } int j; Planet SolarSystem[10]; // 假设你已提前定义该结构体数组 for(j=0; j<10; j++) { // 修正:传入文件指针 + 给非char数组字段传地址 int readCount = fscanf(inputFile, "%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); // 调试用:检查是否成功读取所有字段 if(readCount != 7) { printf("Warning: 第%d个行星数据读取不完整,仅读取了%d个字段\n", j, readCount); break; } } fclose(inputFile); // 关闭文件 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], Pluto[9]\n"); int PlanetNum; scanf("%d",&PlanetNum); printf("You have chosen %s", SolarSystem[PlanetNum].Planet_Name);
现在你再运行程序,应该就能正确读取文件里的行星数据了!
内容的提问来源于stack exchange,提问作者Liam
相关产品推荐
相关产品推荐

