According to K&R C section 1.6, a char
is a type of integer. So why do we need %c
. And why can't we use %d
for everything?
Because %d
will print the numeric character code of the char
:
printf("%d", 'a');
prints 97
(on an ASCII system), while
printf("%c", 'a');
prints a
.
While it's an integer, the %c
interprets its numeric value as a character value for display. For instance for the character a
:
If you used %d
you'd get an integer, eg, 97, the internal representation of the character a
vs
using %c
to display the character ' a
' itself (if using ASCII)
Ie, it's a matter of internal representation vs interpretation for external purposes (such as with printf
)
Roughly speaking, %c
prints the ASCII representation of the character. %d
prints its decimal value.
If you use %c
, you'll print (or scan) a character, or char. If you use %d
, you'll print (or scan) an integer.
printf("%d", 0x70);
How will the machine would know that you want to output a character, not its equivalent ASCII value?
%d认为char是32位并打印它像一个整数,但%c将char的int值转换为ascii字符然后打印它。
%d
用于打印decimal(integer)
数字,而%c
用于打印character
。如果您尝试打印%d
格式的字符,计算机将打印该ASCII
代码。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.