简体   繁体   中英

Why does sscanf read more than expected?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM