Failed to read integer using fscanf in c

2019-07-18 04:24发布

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?

标签: c scanf
1条回答
劳资没心,怎么记你
2楼-- · 2019-07-18 04:59

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.

查看更多
登录 后发表回答