下面的代码是什么意思,在C语言中
scanf("%d%#d%d",&a,&b,&c);
如果给定值 1 2 3
则输出为 1 0 0
P.S- 我知道它与 printf()
语句一起使用,但在 scanf()
语句中它给出了随机行为。
最佳答案
TL;DR; - %
符号后的 #
在 scanf()
的格式字符串中函数是错误的代码。
解释:
这里的#
是一个flag字符,它在fprintf()
和family中是允许的,在fscanf()中是不允许的
和家人。
对于您的代码,%
之后的 #
被视为无效的转换说明符。根据 7.21.6.2,
If a conversion specification is invalid, the behavior is undefined
因此,您的代码生成 undefined behaviour .
提示:您可以检查 scanf()
的 return
值,以检查成功“扫描”了多少元素。
但是,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 both0
, a single0
is printed). Forx
(orX
) conversion, a nonzero result has0x
(or0X
) prefixed to it. Fora
,A
,e
,E
,f
,F
,g
, andG
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.) Forg
andG
conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.
关于c - scanf() 函数中 % 符号后的 # 符号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892463/