在一本C语言书中提到,char数据类型可以存储数字和ASCII字符。计算机如何知道我是引用了一个字符还是一个数字?例如,如果我想在屏幕上打印一个char变量的值,计算机如何知道我是指该数字的ASCII字符还是该数字本身?
谢谢。
谢谢。
printf("This is a char:%c\n", 'c');
printf("This is an int:%d\n", 3);
printf("This is a char:%c\n", 1); // WARNING: Implicit conversion from (int) to (char) (due to implicit down-cast)
如果您提供了一个小于预期的参数,例如:
在详细程度上,您可能不会收到此类编译器警告:
printf("This is an int:%d\n", 'b'); // Implicit up-cast
printf("This is a char:%c\n", 99); // Prints the 'c' character literal
因此,如果字符集是ASCII(即以下示例针对ASCII),则以下内容有效。声明为字符(
char
)的对象足够大,可以存储执行字符集中的任何成员。如果真正的字符来自该集合并存储在char
对象中,则它的值等同于字符的整数代码,并且是非负的。
int n = 65; //is equal to 'A' in ASCII
char c = 'A'; //is equal to 65 in ASCII
printf("%c %d", n, c); //should print "A 65" despite the "wrong" order
printf
函数”部分,对于'%c'格式说明符,printf函数执行以下操作:将int
转换为unsigned char
。
int
;单个字符,在转换为unsigned char
之后。
printf()
提供格式。char c = 'c';
printf("%c \n", c); //result is the character 'c'.
printf("%d \n", c); //result is 99, the ASCII value of character 'c'.
scanf("%d \n", &c); //NEVER do this.
cout<<c;
会打印字符,cout<<(int)c;
会打印ASCII值。 - SHR