Nikola Butigan
Nikola Butigan

Reputation: 35

Error while trying to read from file C

I have a file and i need to read data from it. I have to read 2 int and 1 c string. This is my struct

typedef struct seats
{
int number, reserved;
char * name;
} seats;

This is my main

FILE *data;
seats input;
data = fopen("data.txt", "r+");
while(fscanf(data,"%s %d %d", input.name, &input.number, &input.reserved) != EOF)
{
    printf("%s %d %d", input.name, input.number, input.reserved);
}

Every time when i compile and run this software it crashes for some reason. Is there any solution?

Upvotes: 0

Views: 51

Answers (2)

Nestor Daniel Flores
Nestor Daniel Flores

Reputation: 140

Change your struct to something like this:

typedef struct seats{
    int number, reserved;
    char name[1000];
} seats;

and put a fflush(stdin), after printf(...)

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182837

You haven't assigned any value to input.name, but you pass its garbage value to fscanf. You need to assign a variable a value before you attempt to use that value.

Upvotes: 1

Related Questions