C语言 如何在C中将整数转换为字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2279379/
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 04:31:11  来源:igfitidea点击:

How to convert integer to char in C?

c

提问by anik

How to convert integer to char in C?

如何在C中将整数转换为字符?

回答by Ofir

A char in C is already a number (the character's ASCII code), no conversion required.

C 中的字符已经是一个数字(字符的 ASCII 代码),不需要转换。

If you want to convert a digit to the corresponding character, you can simply add '0':

如果要将数字转换为相应的字符,只需添加“0”即可:

c = i +'0';

The '0' is a character in the ASCll table.

'0' 是 ASCll 表中的一个字符。

回答by ratty

You can try atoi() library function. Also sscanf() and sprintf() would help.

您可以尝试 atoi() 库函数。sscanf() 和 sprintf() 也会有所帮助。

Here is a small example to show converting integer to character string:

这是一个小示例,用于显示将整数转换为字符串:

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
  // Now str contains the integer as characters
} 

Here for another Example

这是另一个例子

#include <stdio.h>

int main(void)
{
   char text[] = "StringX";
   int digit;
   for (digit = 0; digit < 10; ++digit)
   {
      text[6] = digit + '0';
      puts(text);
   }
   return 0;
}

/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

回答by Amarghosh

Just assign the intto a charvariable.

只需将 分配int给一个char变量。

int i = 65;
char c = i;
printf("%c", c); //prints A

回答by Deepak Yadav

To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence

要将整数转换为字符,只有 0 到 9 会被转换。我们知道 0 的 ASCII 值是 48,所以我们必须将它的值添加到整数值中以转换为所需的字符,因此

int i=5;
char c = i+'0';

回答by Anurag Semwal

To convert int to char use:

要将 int 转换为 char 使用:

int a=8;  
char c=a+'0';
printf("%c",c);       //prints 8  

To Convert char to int use:

要将 char 转换为 int 使用:

char c='5';
int a=c-'0';
printf("%d",a);        //prints 5

回答by kannadasan

 void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);


     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }