gpt4 book ai didi

c - %% 应该跳过 scanf 中的前导空格吗?

转载 作者:太空狗 更新时间:2023-10-29 15:25:27 24 4
gpt4 key购买 nike

根据C17 7.21.6.2/8中fscanf的规范:

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

如果格式字符串包含%%,则它是带有% 说明符的规范。这不是 [cn,因此标准似乎表示应在此处跳过前导空格。

我的问题是:这是正确的解释,还是标准中的缺陷?

我测试了两种不同的实现(带有 MSVCRT stdio 的 mingw-w64 和带有 MinGW stdio 的 mingw-w64)。前者不跳过前导空格,后者跳过。

测试代码:

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

最佳答案

它应该跳过空格。

规范中有一个示例专门说明应该跳过空格:

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.

关于c - %% 应该跳过 scanf 中的前导空格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53200858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com