关于c ++:格式化的IO函数(* printf / * scanf)中的转换说明符%i和%d有什么区别

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

printf中用作格式说明符时,%d%i之间有什么区别?


当用于输出时它们是相同的,例如与printf

但是,当用作输入说明符时,它们是不同的。使用scanf,其中%d扫描整数作为有符号十进制数字,但是%i默认为十进制,但也允许十六进制(如果以0x开头)和八进制(如果以0开头)。

所以033对于%i将为27,而对于%d为33。


对于printf,这些相同,但对于scanf,则不同。对于printf%d%i均指定一个带符号的十进制整数。对于scanf%d%i也表示带符号的整数,但是%i如果以0x开头则将输入解释为十六进制数,如果以0开头则以八进制解释,否则将输入解释为十进制。


printf%i%d格式说明符之间没有区别。我们可以从C99标准草案的7.19.6.1部分看到fprintf函数,该函数在格式说明符方面也涵盖了printf,它在第8段中说:

The conversion specifiers and their meanings are:

并包括以下项目符号:

1
2
3
4
5
6
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段中说:

The conversion specifiers and their meanings are:

并包括以下内容:

1
2
3
4
5
6
7
8
9
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中没有任何内容-这两个是同义词。