scanf() 函数中 % 符号后的 # 符号是什么意思?

What does a # sign after a % sign in a scanf() function mean?

下面的代码是什么意思,在C语言中

scanf("%d%#d%d",&a,&b,&c);

如果给定值 1 2 3 则输出为 1 0 0

P.S- 我知道它与 printf() 语句一起使用,但在 scanf() 语句中它给出了随机行为。

根据 the Standard,使用 # 是非法的。

Its use makes your program invoke Undefined Behaviour.

当然,如果你的实现定义了它,它就是为你的实现定义的行为并且它做了你的文档说。

TL;DR; - scanf() 函数格式字符串中 % 符号后的 # 是错误代码。

解释:

这里的#是一个flag字符,在fprintf()和family中是允许的,在fscanf()和family中是不允许的。

对于您的代码,% 之后 # 的存在被视为 无效的转换说明符 。根据 7.21.6.2,

If a conversion specification is invalid, the behavior is undefined

因此,您的代码生成 undefined behaviour.

提示:可以查看scanf()return值,查看有多少个元素"scanned"成功。


但是,FWIW,在 printf() 中使用 #%d 也是 undefined behaviour

仅供参考:根据 C11 标准文档,第 §7.21.6.1 章,标志字符部分,(强调我的)

#

The result is converted to an ‘‘alternative form’’. For o conversion, it increases the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point character, even if no digits follow it. (Normally, a decimal-point character appears in the result of these conversions only if a digit follows it.) For g and G conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.