[英]C int to char not printing out using char format
I'm trying to print out the digits of an integer using the char format specifier.我正在尝试使用 char 格式说明符打印出整数的数字。
This is what I currently have这是我目前拥有的
//counter = arbitrary int
while (counter > 0) {
char c = (char)(counter % 10);
printf("%c", c);
counter/=10;
}
This just prints out blank but if I change the format specifier to int but leave the type cast, it'll print the correct value.这只是打印出空白,但如果我将格式说明符更改为 int 但保留类型转换,它将打印正确的值。 Something like this
像这样的东西
char c = (char)(counter % 10);
printf("%d", c);
Any ideas why this isn't printing when I use the char format specifier?当我使用 char 格式说明符时,为什么不打印的任何想法?
%c
is for printing a character, not a number. %c
用于打印字符,而不是数字。 If you want to print a number, you should use %d
.如果你想打印一个数字,你应该使用
%d
。 The reason it works for char
is because char
is implicitly promoted to int
when you pass it as an argument to a variadic function.它适用于
char
的原因是因为当您将其作为参数传递给可变参数函数时, char
被隐式提升为int
。
If c
contained 'A'
, and you used %c
to format it, you would get the letter 'A', but if you used %d
, you would get its integer value, eg 65.如果
c
包含'A'
,并且您使用%c
进行格式化,您将获得字母 'A',但如果您使用%d
,您将获得它的整数值,例如 65。
If you absolutely must use %c
, you can add the value of '0'
to the character before printing, egL如果您绝对必须使用
%c
,则可以在打印前将'0'
的值添加到字符中,例如
printf("%c", c + '0');
%c
可以在此上下文中用作printf("%c",c+'0')
,其中+'0'
将其转换为与c
等效的整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.