格式化IO函數(shù)中的轉換說明符%i和%d之間有什么區(qū)別(* printf / * scanf)%d和%i用作格式說明符的區(qū)別是什么printf?
3 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
當用于輸出時它們是相同的,例如printf
。
但是,當用作輸入說明符時,這些是不同的,例如scanf
,其中,%d
將整數(shù)掃描為帶符號的十進制數(shù),但%i
默認為十進制,但也允許十六進制(如果前面帶有0x
)和八進制(如果前面帶有0
)。
所以033
27 %i
歲,但33歲%d
。

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
%i
和%d
格式說明符之間沒有區(qū)別printf
。我們可以通過參考草案C99標準部分來看到這一點7.19.6.1
.fprintf函數(shù)也涉及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
假設基數(shù)為10而%i
自動檢測基數(shù)。我們可以通過將部分看到這個7.19.6.2
fscanf函數(shù)覆蓋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.

忽然笑
TA貢獻1806條經驗 獲得超5個贊
在我看來,在sscanf中可能出現(xiàn)零填充的int似乎是最合理的默認行為。如果你不期待Octal,那可能會導致微妙的錯誤。所以這表明%d是一個很好的說明符,當你必須任意選擇一個時,除非你明確想要讀取八進制和/或十六進制。
- 3 回答
- 0 關注
- 1114 瀏覽
添加回答
舉報
0/150
提交
取消