0

I am trying to convert integer into character. I know how to convert character to integer like this int(a) where a is a character. But when I am trying to convert integer to character, it is giving me a symbolic value. Please help me out.

I am doing something like below. Thanks in advance.

int a=0;
char str1[20];
for(int i=0;i<size;i++)
   //somecalculation that sets value in a everytime and stores in str1 
   str1[i]=char(a)-'A'

Well I am running for loop and setting values in str1. This is just little of my code.

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
user3215228
  • 313
  • 1
  • 3
  • 13

2 Answers2

1

You could use str1[i] = static_cast<char>(a + '0');. This will convert a = 0 to '0', a = 1 to '1' etc. Consider the behaviour as undefined outside the range 0, ..., 9.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

just use sprintf:

for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1 
    sprintf(str1 + i, "%i", a);

since you noted that a is each time only a one digit integer, this should work, but this is not very error prone... normally you should check on how much digits were written:

for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1 
    if (sprintf(str1 + i, "%i", a) != 1)
        printf("expected to print only one character!\n");
Chris Maes
  • 35,025
  • 12
  • 111
  • 136