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

标签 c input scanf format-specifiers

下面的代码是什么意思,在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 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.

关于c - scanf() 函数中 % 符号后的 # 符号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892463/

相关文章:

html - 问题系统的 CSS 输入字段和按钮位置

c - IA32 - 如何查看调用 sscanf() 的参数?

c - scanf 格式字符串无法识别

c - 在其他源文件中定义的外部变量和结构

c# - 为什么 C#(相当慢)和 Win32/C 之间的性能差异?

c - 如果我将 printf 方法中的所有 %X 替换为 %p 会怎样

c - GLSL统一 float 未正确传递

c++ - 当我不需要 C++ 计算时如何忽略某些输入?

html - HTML 5 的输入类型电子邮件如何工作并且可靠吗?

c - while 循环第二次忽略 scanf