[英]Format Specifiers in C and their Roles?
wrote this code to "find if the given character is a digit or not"编写此代码以“查找给定字符是否为数字”
#include<stdio.h>
int main()
{
char ch;
printf("enter a character");
scanf("%c", &ch);
printf("%c", ch>='0'&&ch<='9');
return 0;
}
this got compiled, but after taking the input it didn't give any output.这已编译,但在接受输入后它没有给出任何输出。 However, on changing the %c in the second last line to %d format specifier it indeed worked.但是,在将倒数第二行中的%c更改为%d格式说明符时,它确实有效。 I'm a bit confused as in why %d worked but %c didn't though the variable is of character datatype.我有点困惑,为什么 %d 有效,但 %c 却没有,尽管变量是字符数据类型。
Characters in C are really just numbers in a token table. C 中的字符实际上只是令牌表中的数字。 The %c
is mainly there to do the translation between the alphanumeric token table that humans like to read/write and the raw binary that the C program uses internally. %c
主要用于在人类喜欢读/写的字母数字标记表和 C 程序内部使用的原始二进制文件之间进行转换。
The expression ch>='0'&&ch<='9'
evaluates to 1
or 0
which is a raw binary integer of type int
(it would be type bool
in C++).表达式ch>='0'&&ch<='9'
计算结果为1
或0
,这是int
类型的原始二进制整数(在 C++ 中为bool
类型)。 If you attempt to print that one with %c
, you'll get the symbol table character with index 0 or 1, which isn't even a printable character (0-31 aren't printable).如果您尝试使用%c
打印该字符,您将获得索引为 0 或 1 的符号表字符,这甚至不是可打印字符(0-31 不可打印)。 So you print a non-printable character... either you'll see nothing or you'll see some strange symbols.所以你打印一个不可打印的字符......要么你什么都看不到,要么你会看到一些奇怪的符号。
Instead you need to use %d
for printing an integer, then printf
will do the correct conversion to the printable symbols '1'
and '0'
相反,您需要使用%d
打印整数,然后printf
将正确转换为可打印符号'1'
和'0'
As a side-note, make it a habit to always end your (sequence of) printf statements with \n
since that "flushes the output buffer" = actually prints to the screen, on many systems.作为旁注,养成始终以\n
结束(序列) printf 语句的习惯,因为在许多系统上,“刷新输出缓冲区”=实际上打印到屏幕上。 See Why does printf not flush after the call unless a newline is in the format string?请参阅为什么 printf 在调用后不刷新,除非换行符在格式字符串中? for details详情
在内存中, int 占用 4 个字节的内存,您试图将 int 值存储在一个字符中,如果您使用 %d,它将返回 ascii 值而不是 %c 中的 int 值,这将返回正在存储的 int 值在4字节内存的内存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.