In C is there a way to convert an ASCII value typed as an int into the the corresponding ASCII character as a char?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can assign int
to char
directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
回答2:
If i
is the int
, then
char c = i;
makes it a char
. You might want to add a check that the value is <128
if it comes from an untrusted source. This is best done with isascii
from <ctype.h>
, if available on your system (see @Steve Jessop's comment to this answer).
回答3:
If the number is stored in a string (which it would be if typed by a user), you can use atoi()
to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");