Should %% skip leading whitespace in scanf?

2019-06-26 06:03发布

问题:

According to the specification of fscanf in C17 7.21.6.2/8:

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [ , c , or n specifier

If the format string contains %%, then it is a specification with a % specifier. That isn't [, c, or n, so the standard appears to say that leading whitespace should be skipped here.

My question is: is this a correct interpretation, or is it a defect in the standard?

I tested two different implementations (mingw-w64 with MSVCRT stdio, and mingw-w64 with MinGW stdio). The former did not skip leading whitespace, the latter did.

Test code:

#include <stdio.h>

int main(void)
{
    int a, r;

    // Should be 1 according to standard; would be 0 if %% does not skip whitespace
    r = sscanf("x %1", "x%% %d", &a);
    printf("%d\n", r);

    // Should always be 1
    r = sscanf("x%1", "x%% %d", &a);
    printf("%d\n", r);
}

回答1:

It should skip whitespace.

The specification has an example that says specifically that whitespace should be skipped:

EXAMPLE 5 The call:

#include <stdio.h>
/* ... */
int n, i;
n = sscanf("foo %bar 42", "foo%%bar%d", &i);

will assign to n the value 1 and to i the value 42 because input white-space characters are skipped for both the % and d conversion specifiers.