2009-12-12 44 views

回答

216

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

但是,当用作输入说明符时,这些是不同的。与scanf,其中%d扫描一个整数作为带符号的十进制数,但%i默认为十进制,但也允许十六进制(如果前面有0x)和八进制(如果前面跟着0)。

因此033将27与%i但33与%d

+4

在sscanf中期待一个int可能的零填充在我看来是最合理的默认行为。如果你不期待Octal,那可能会导致微妙的错误。所以这表明当你必须任意选择一个时,%d是一个很好的说明符,除非你明确地想要读八进制和/或十六进制。 – Eliot

9

这些词中没有任何 - 这两个词是同义词。

+0

在接受的答案中提到,在scanf()格式的字符串中使用时有区别。 –

62

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

14

对于printf%i%d格式说明符之间没有区别。我们可以通过转到draft C99 standard部分7.19.6.1fprintf函数又包括printf关于格式说明看到这一点,它在一段说:

转换标识符和它们的含义如下:

,并包括以下子弹:

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.2fscanf函数覆盖scanf关于格式说明看到这个,在第它说:

转换标识符和它们的含义如下:

并且包括以下:

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. 
相关问题