Why does sscanf read more than expected?

Viewed 65

sscanf supports %n to count how many bytes are read.

Why does sscanf sometimes read additional bytes?

#include <stdio.h>

int main()
{
    char *data = "X\n \n\x09\n \x10\n";
    int len = 0;

    sscanf(data, "X%n", &len);
    printf("%i\n", len);

    sscanf(data, "X\n%n", &len);
    printf("%i\n", len);

    return 0;
}

This program prints:

1
7

I would expect:

1
2

(1 for X and 2 for X\n.)

Why does it read more bytes than expected?

1 Answers

From cppreference:

The format string consists of

  • non-whitespace multibyte characters except %: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.

  • whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling isspace in a loop). Note that there is no difference between "\n", " ", "\t\t", or other whitespace in the format string.

Thus, your \n in the second format string will cause the function to consume all remaining whitespace characters – which is actually all 6 characters following the X and preceding the 0x10.

Related