为什么 sscanf 读取的内容比预期的多?
Why does sscanf read more than expected?
sscanf
支持%n
统计读取了多少字节
为什么 sscanf 有时会读取额外的字节?
#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;
}
这个程序打印:
1
7
我预计:
1
2
(X
为 1,X\n
为 2。)
为什么读取的字节比预期的多?
来自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.
因此,第二个格式字符串中的 \n
将导致函数消耗所有剩余的空白字符——实际上是 X
之后和 0x10
之前的所有 6 个字符.
sscanf
支持%n
统计读取了多少字节
为什么 sscanf 有时会读取额外的字节?
#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;
}
这个程序打印:
1
7
我预计:
1
2
(X
为 1,X\n
为 2。)
为什么读取的字节比预期的多?
来自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.
因此,第二个格式字符串中的 \n
将导致函数消耗所有剩余的空白字符——实际上是 X
之后和 0x10
之前的所有 6 个字符.