简体   繁体   English

从txt文件读入数组

[英]Reading into an array from a txt file

So, I'm trying to get my program to read into an array of structs from a text file, and it compiles okay, but doesnt appear to actually be reading in the values?.. and I have no idea why. 因此,我正在尝试让我的程序从文本文件中读取结构数组,并且可以编译,但是似乎没有真正在读取值?。我不知道为什么。 This is the relevant part of the code: 这是代码的相关部分:

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

This is the txt file (Title: Planets.txt) 这是txt文件(标题:Planets.txt)

Mercury 120 50 500 12.1 30 2 Venus 120 50 500 29.1 30 6 Earth 120 50 500 32.2 30 7 Moon 120 15 50 5.3 30 2 Mars 120 50 500 12.2 30 4 Jupiter 120 50 500 81.3 30 10 Saturn 120 50 500 34.3 30 8 Uranus 120 50 500 28.5 30 5 Neptune 120 50 500 36.6 30 9 Pluto 120 50 500 2.03 30 1 汞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

Except when it runs that final printf, it doesn't actually print anything, nor does it store any data in the structs (when its called later it's all zeroes). 除了运行最终的printf时,它实际上不打印任何内容,也不在结构中存储任何数据(以后调用时,它们全为零)。 Ideas? 想法?

The mistake is with your fscanf function . 错误在于您的fscanf函数。 You have to provide FILE pointer ( inputFile This context) as first argument and & operator(address of Similar to scanf function) in front of scanning integer and float. 您必须在扫描整数和浮点数之前提供FILE pointerinputFile此上下文)作为第一个参数,并提供&运算符(类似于scanf函数的地址)。

Try this modified fscanf code :- 试试这个修改过的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM