%%是否应跳过scanf中的前导空白? [英] Should %% skip leading whitespace in scanf?

查看:152
本文介绍了%%是否应跳过scanf中的前导空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to the specification of fscanf in C17 7.21.6.2/8:

除非规范包含[cn说明符,否则将跳过输入的空白​​字符(由isspace函数指定).

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

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

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?

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

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.

测试代码:

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

推荐答案

应跳过空格.

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

The specification has an example that says specifically that whitespace should be skipped:

示例5通话:

EXAMPLE 5 The call:

#include <stdio.h>
/* ... */
int n, i;
n = sscanf("foo %bar 42", "foo%%bar%d", &i);

将为n分配1值,并为i分配42值,因为两个输入字符都被跳过 %d转换说明符.

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.

这篇关于%%是否应跳过scanf中的前导空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆