简体   繁体   中英

Fscanf from .txt in C

I have to scanf eg 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.

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 int s.

The same with printf :

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

Live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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