是否应跳过scanf中的前导空白

是否应跳过scanf中的前导空白

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

问题描述

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

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

如果格式字符串包含%%,则它是带有%指定符的规范.不是[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:

#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中的前导空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:21