program story

C에서 정수를 문자로 변환하는 방법은 무엇입니까?

inputbox 2020. 12. 29. 07:03
반응형

C에서 정수를 문자로 변환하는 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

C에서 정수를 문자로 변환하는 방법은 무엇입니까?


C의 문자는 이미 숫자 (문자의 ASCII 코드)이며 변환이 필요하지 않습니다.

숫자를 해당 문자로 변환하려면 '0'을 추가하면됩니다.

c = i +'0';

'0'은 ASCll 테이블의 문자입니다.


atoi () 라이브러리 함수를 사용해 볼 수 있습니다. 또한 sscanf () 및 sprintf ()가 도움이 될 것입니다.

다음은 정수를 문자열로 변환하는 것을 보여주는 작은 예입니다.

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

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

여기에 또 다른 예

#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
*/

변수에 int할당하십시오 char.

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

정수를 문자로 변환하려면 0에서 9까지만 0으로 변환됩니다. ASCII 값은 48이므로 원하는 문자로 변환 할 값을 추가해야합니다.

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

int를 char로 변환하려면 다음을 사용하십시오.

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

char를 int로 변환하려면 다음을 사용하십시오.

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

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

 }

ReferenceURL : https://stackoverflow.com/questions/2279379/how-to-convert-integer-to-char-in-c

반응형