如何将char转换为int,反之亦然?

如何将char转换为int,反之亦然?,c,char,type-conversion,integer,C,Char,Type Conversion,Integer,我希望在不使用输出格式的情况下将字符转换为int,反之亦然。我该怎么做呢?你说的是像“1”或“9”这样的一位数字符吗?然后你会这样做: char c = '5'; int x = c - '0'; // x == 5 数字编码在所有字符编码方案ASCII、EBCDIC等中都是连续的,因此减去“0”的代码可以得到正确的值 你是说把字符编码转换成整数吗?然后,只需将字符值指定给int: 你是说转换一个字符串,比如12或42?然后您需要使用sscanf、strtol或atoi库函数之

我希望在不使用输出格式的情况下将字符转换为int,反之亦然。我该怎么做呢?

你说的是像“1”或“9”这样的一位数字符吗?然后你会这样做:

char c = '5';      
int  x = c - '0';  // x == 5
数字编码在所有字符编码方案ASCII、EBCDIC等中都是连续的,因此减去“0”的代码可以得到正确的值

你是说把字符编码转换成整数吗?然后,只需将字符值指定给int:

你是说转换一个字符串,比如12或42?然后您需要使用sscanf、strtol或atoi库函数之一,或者使用您自己的等效函数。给定

char str[] = "123";
int x;
你会的

sscanf( str, "%d", &x ); 


如果要打印字符的ASCII值

 char c1 = 'A';
 printf("%d",(int)c1);     //Prints ASCII value of character 'A' = (65)
char c1 = 'A';
printf("%d ",c1);         //Prints ASCII value of character 'A' = (65)
char c2 = '5';
int x = c2-'0';
printf("%d",x); //prints integer value of character '5'(5)
下面的代码还打印字符的ASCII值

 char c1 = 'A';
 printf("%d",(int)c1);     //Prints ASCII value of character 'A' = (65)
char c1 = 'A';
printf("%d ",c1);         //Prints ASCII value of character 'A' = (65)
char c2 = '5';
int x = c2-'0';
printf("%d",x); //prints integer value of character '5'(5)
如果要打印字符的值

 char c1 = 'A';
 printf("%d",(int)c1);     //Prints ASCII value of character 'A' = (65)
char c1 = 'A';
printf("%d ",c1);         //Prints ASCII value of character 'A' = (65)
char c2 = '5';
int x = c2-'0';
printf("%d",x); //prints integer value of character '5'(5)

intc工作得很好。c-“0”也可以工作。请详细说明您的问题。给出预期输入和输出的示例。只需转换变量。字符c;int i=25;c=字符i;my_char='10'my_int=intmy_var;my_str=strmy_int;如果无法转换python,则引发ValueError