用printf打印一个字符 [英] Printing a char with printf
问题描述
这两个代码是否相同
char ch = 'a';
printf("%d", ch);
会打印垃圾值吗?
对此我感到困惑
printf("%d", '\0');
这将打印0还是垃圾值?因为当我这样做
Will this print 0 or garbage value? Because when i do this
printf("%d", sizeof('\n'));
它打印4.为什么 sizeof('\ n')
4个字节?在C ++中,相同的东西打印1个字节.为什么会这样?
It prints 4. Why is sizeof('\n')
4 bytes?
The same thing in C++ prints 1 bytes. Why is that?
所以这是主要问题
是 printf(%d",'\ 0')
应该打印0
以及在C ++中应该打印垃圾的printf(%d",'\ 0')?
and in C++ printf("%d", '\0')
supposed to print garbage?
推荐答案
%d
打印整数:它将打印字符的ascii表示形式.您需要的是%c
:
%d
prints an integer: it will print the ascii representation of your character. What you need is %c
:
printf("%c", ch);
printf(%d",'\ 0');
打印'\ 0'
的ascii表示形式,即0(通过转义0可以告诉编译器使用ascii值0.
printf("%d", '\0');
prints the ascii representation of '\0'
, which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.
printf(%d",sizeof('\ n'));
打印4,因为字符文字是C中的 int
,而不是<代码>字符代码>.
printf("%d", sizeof('\n'));
prints 4 because a character literal is an int
, in C, and not a char
.
这篇关于用printf打印一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!