programing

C에서 정수를 문자로 변환하는 방법

sourcetip 2022. 7. 19. 23:30
반응형

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

 }

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

반응형