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

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

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

但是,当用作input说明符(例如scanf时,这些不同,其中%d扫描整数作为带符号的十进制数,但是%i默认为十进制数,但也允许使用hex(如果前面有0x )和八进制(前面有0

所以033将会是%i 27,而%i 33是33。

这些对于printf是相同的,但对于scanf是不同的。 对于printf%d%i指定一个带符号的十进制整数。 对于scanf%d%i也表示一个有符号的整数,但%i将input解释为hex数(如果前面是0x和八进制(前面是0 ,否则将input解释为十进制。

printf%i%d格式说明符之间没有区别。 我们可以通过转到C99标准草案部分7.19.6.1来看到这一点7.19.6.1 函数也涵盖了关于格式说明符的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节来看到这一点。关于格式说明符覆盖scanf 的fscanf函数 ,在第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. 

这些话中没有任何一个 – 两个是同义词。