Failed to read integer using fscanf in c

2019-07-18 04:43发布

问题:

FILE *fin = fopen("figura.in", "r");
if(fscanf(fin, "%d %d %d %d", &int[0], &int[1], &int[2], &int[3]) == 1)     {
        printf("%d\t%d\t%d\t%d\n", int[0], int[1], int[2], int[3]);
    } else {
        printf("failed to read integer.\n");
    }

I get failed to read integer. The file is okay, it consists 4 integers. What is wrong?

回答1:

You should be checking to see if fscanf returns 4, the number of inputs in your format string:

if(fscanf(fin, "%d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3]) == 4) 

From the man page:

return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.



标签: c scanf