【发布时间】:2010-12-25 23:53:27
【问题描述】:
%d 和%i 在printf 和scanf 中用作格式说明符时有什么区别?
【问题讨论】:
标签: c++ c printf scanf format-specifiers
%d 和%i 在printf 和scanf 中用作格式说明符时有什么区别?
【问题讨论】:
标签: c++ c printf scanf format-specifiers
它们在用于输出时是相同的,例如printf。
但是,当用作输入说明符时,这些是不同的,例如使用scanf,其中%d 将整数扫描为带符号的十进制数,但%i 默认为十进制,但也允许使用十六进制(如果前面有0x)和八进制(如果前面有0)。
所以033 将是 27 与 %i 但 33 与 %d。
这些对于printf 是相同的,但对于scanf 是不同的。对于printf,%d 和%i 都指定有符号十进制整数。对于scanf、%d 和%i 也表示有符号整数,但%i 如果前面有0x 则将输入解释为十六进制数,如果前面有0 则将输入解释为八进制数,否则将输入解释为十进制。
【讨论】:
printf 的 %i 和 %d 格式说明符之间没有区别。我们可以通过转到draft C99 standard 部分7.19.6.1 fprintf 函数 看到这一点,它还涵盖了printf 关于格式说明符,它在第 8 段中说:
转换说明符及其含义为:
并包括以下项目符号:
d,i The int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
另一方面,scanf 存在差异,%d 假设基数为 10,而 %i 自动检测基数。我们可以通过转到7.19.6.2 部分来看到这一点fscanf 函数 涵盖了scanf 关于格式说明符,在第12 段中它说:
转换说明符及其含义为:
并包括以下内容:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
【讨论】:
printf 中没有任何内容 - 两者是同义词。
【讨论】:
scanf()格式字符串中使用时会有所不同。