Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning strings with fscanf in C

Tags:

c

string

file

scanf

Please, help me to fix some problems.

The file contains:

AAAA 111 BBB
CCC 2222 DDDD
EEEEE 33 FF

The code is:

int main() {
    FILE * finput;

    int i, b;
    char a[10];
    char c[10];

    finput = fopen("input.txt", "r");

    for (i = 0; i < 3; i++) {
        fscanf(finput, "%s %i %s\n", &a, &b, &c);
        printf("%s %i %s\n", a, b, c);
    }

    fclose(finput);
    return 0;
}

The code does work. However, the following errors occur:

format «%s» expects argument of type «char *», but argument 3 has type «char (*)[10]
format «%s» expects argument of type «char *», but argument 5 has type «char (*)[10]

Are the types wrong? What's the problem?

like image 659
kimalser Avatar asked Jan 16 '23 05:01

kimalser


1 Answers

Array names decay to a pointer to their first element, so in order to pass the addresses of the arrays to fscanf(), you should simply pass the arrays directly:

fscanf(finput, "%s %i %s\n", a, &b, c);

This is equivalent to:

fscanf(finput, "%s %i %s\n", &a[0], &b, &c[0]);

But obviously using a instead of &a[0] is more convenient.

The way you wrote it, you're passing the same value (that's why it works), but that value has a different type: it's not a pointer to a char anymore, but a pointer to an array of chars. That's not what fscanf() is expecting, so the compiler warns about it.

For an explanation, see: https://stackoverflow.com/a/2528328/856199

like image 68
Nikos C. Avatar answered Jan 25 '23 13:01

Nikos C.