Momo
Momo

Reputation: 55

Fscanf from .txt in C

I have to scanf e.g. this line of text from .txt file (upload is correct):

[1,1] v=5 s=4#o`

And this is my code:

typedef struct {
    int red2[10];
    int stupac2[10];
    int visina[10];
    int sirina[10];
    char boja[10];

} Tunel;
FILE *fin = fopen("farbanje.txt", "r");
Tunel *tuneli = (Tunel *)malloc(sizeof(Tunel) * 200);

int p = 0;

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2, tuneli[p].stupac2) == 2)
{
    printf("%d %d", tuneli[p].red2, tuneli[p].stupac2);
    p++;
}

I wanted to check only 2 parameters from .txt but it gives me some random values.

Upvotes: 1

Views: 50

Answers (1)

anastaciu
anastaciu

Reputation: 23792

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2, tuneli[p].stupac2) == 2)

Is wrong, the member variables of the struct are arrays and you need to pass them to scanf as such, for example:

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2[0], &tuneli[p].stupac2[0]) == 2)

Or make the member variables single ints.

The same with printf:

printf("%d %d", tuneli[p].red2[0], tuneli[p].stupac2[0]);

Live demo

Upvotes: 1

Related Questions