Should %% skip leading whitespace in scanf?

3226 views c

According to the specification of fscanf in C17

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);

answered question

1 Answer


It should skip whitespace.

I don't have a copy of the C17 specification, but the online WG14 C11 draft 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.

posted this

Have an answer?


Please login first before posting an answer.