C语言 将 ASCII 数字转换为 C 中的 ASCII 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6660145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:06:49  来源:igfitidea点击:

Convert ASCII number to ASCII Character in C

ctypesascii

提问by Anonymous

In C is there a way to convert an ASCII value typed as an int into the the corresponding ASCII character as a char?

在 C 中有没有办法将输入为 int 的 ASCII 值转换为相应的 ASCII 字符作为字符?

回答by taskinoor

You can assign intto chardirectly.

您可以分配intchar直接。

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

事实上,这也将起作用。

printf("%c", a);  // assuming a is in valid range

回答by Fred Foo

If iis the int, then

如果iint,那么

char c = i;

makes it a char. You might want to add a check that the value is <128if it comes from an untrusted source. This is best done with isasciifrom <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

使其成为char. 您可能想要添加检查值<128是否来自不受信任的来源。如果在您的系统上可用,最好使用isasciifrom完成<ctype.h>(请参阅@Steve Jessop 对此答案的评论)。

回答by Jonathan Wood

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.

如果数字存储在字符串中(如果由用户键入),则可以使用atoi()将其转换为整数。

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");