Liam
Liam

Reputation: 3

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)

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

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). Ideas?

Upvotes: 0

Views: 121

Answers (1)

anoopknr
anoopknr

Reputation: 3355

The mistake is with your fscanf function . 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.

Try this modified fscanf code :-

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

Upvotes: 1

Related Questions