Scanf() - %a format/conversion 说明符是什么?

Scanf() - What is the %a format/conversion specifier?

在 C 中,有机会在 scanf() 格式字符串中实现 %a 作为格式说明符,用于格式化浮点值。

喜欢:

float v;
scanf("%a",&v);

在 C 标准中(我的关系特别是 ISO/IEC 9899/2011 (C11))只是较少解释该特定说明符,并且与 [= 的相关浮点转换说明符没有区别14=]、%e%g :

引文,ISO/IEC 9899/2011,§7.21.6.2:

a,e,f,g - Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

这个说明符是什么意思,它的用途是什么? 与其他浮点转换说明符的具体区别在哪里?

%a%e%f%g 格式说明符到 scanf 都执行相同的转换,如引自标准。

scanf 的 Linux 手册页更明确地说明了这一点:

f Matches an optionally signed floating-point number; the next pointer must be a pointer to float.

e Equivalent to f.

g Equivalent to f.

E Equivalent to f.

a (C99) Equivalent to f.

据推测,这些存在是因为它们也是 printf 接受 float 的格式说明符,但与 scanf 不同的是,它们产生的输出不同。

为了说明这一点,下面的代码:

#include <stdio.h>

int main()
{
    char *str[] = { "234.56", "2.3456e2", "2.3456E2", "0x1.d51eb8p+7" };
    unsigned i;

    for (i=0; i<sizeof(str)/sizeof(*str); i++) {
        float f;

        printf("scanning %s\n", str[i]);
        sscanf(str[i], "%f", &f);
        printf("scanned with f: (f)%f, (e)%e, (g)%g, (a)%a\n", f, f, f, f);
        sscanf(str[i], "%g", &f);
        printf("scanned with g: (f)%f, (e)%e, (g)%g, (a)%a\n", f, f, f, f);
        sscanf(str[i], "%e", &f);
        printf("scanned with e: (f)%f, (e)%e, (g)%g, (a)%a\n", f, f, f, f);
        sscanf(str[i], "%a", &f);
        printf("scanned with a: (f)%f, (e)%e, (g)%g, (a)%a\n", f, f, f, f);
    }
    return 0;
}

输出:

scanning 234.56
scanned with f: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with g: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with e: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with a: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanning 2.3456e2
scanned with f: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with g: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with e: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with a: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanning 2.3456E2
scanned with f: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with g: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with e: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with a: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanning 0x1.d51eb8p+7
scanned with f: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with g: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with e: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7
scanned with a: (f)234.559998, (e)2.345600e+02, (g)234.56, (a)0x1.d51eb8p+7