user3390610
user3390610

Reputation: 31

Error Reading values from a file into array of structures

So i am trying to read values into an array of structs, from a loop. The file has a certain know input, so each I want to assign each value to a specific slot in the array of structures. However, each time I try to run it, I am told that 'expected expression before ROW' in the lines of the loop.

typedef struct information
{
char Poke[100];
char Type[100];
char Evo[100];
float Height;
float Weight;
int HP;
int Attack;
int Defense;
int SPA;
int SPD;
int Speed;
} ROW[100];

int main()
{
     int i;
     FILE *ifp;
     //open file, set to ifp

    while(!feof(ifp))
    {
    j++;
    //Read and store all values
    fscanf(ifp, "%s %s", ROW[j].Poke, ROW[j].Type);
    fscanf(ifp, "%f %f", ROW[j].Height, ROW[j].Weight);
    fscanf(ifp, "%i %i %i %i %i %i", &ROW[j].HP, &ROW[j].Attack,
        &ROW[j].Defense,&ROW[j].SPA,&ROW[j].SPD,&ROW[j].Speed);
    fscanf(ifp, "%s", &ROW[j].Evo[0]);
    } 
}

Upvotes: 1

Views: 75

Answers (2)

M.M
M.M

Reputation: 141648

Adding to Andrew Medico's answer. A better loop structure would be:

for (j = 0;; )
{
    ROW row;
    int n_items = fscanf(ifp, "%100s %100s %f %f......",
        row.Poke, row.Type, &row.Height, &row.Weight, ......);

    if ( n_items == 11 )
        rows[j++] = row;
    else
        break;
}
// at this point, the number of valid rows is j

Another point is that this loop structure cannot gracefully handle the case where you have a typo in your input. It would be better to replace the fscanf line with:

char buffer[400];   // longer than the longest line
if ( ! fgets(buffer, sizeof buffer, ifp) )
    break;

int n_items = sscanf(buffer, "%100s...........

This design is more flexible in that it lets you do some checks on the line before doing sscanf. For example you could support having the # character at the start of a line to mean that the line should be skipped.

Upvotes: 1

nobody
nobody

Reputation: 20174

You can't define a struct and declare an array in one expression like that. You need to split the two up, like this:

typedef struct information
{
    char Poke[100];
    char Type[100];
    char Evo[100];
    float Height;
    float Weight;
    int HP;
    int Attack;
    int Defense;
    int SPA;
    int SPD;
    int Speed;
} ROW;

ROW rows[100];

Then use rows in your loop.

Upvotes: 3

Related Questions