2009-12-12 43 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. 
相關問題