Home > front end >  Array of int to string conversion in C
Array of int to string conversion in C

Time:12-29

I'm trying to convert an array of integers into a string in C. FOr instance I have the following code:

 int number[] = {1,3,2,0};
 char c[5];
 for(int i = 0 ; i < 4; i    ){
        c[i] = number[i];
    }
printf("%s", c);

It however outputs smiley faces or hearts and I am not sure why.

CodePudding user response:

When you printf characters, it takes the ASCII symbol for that number.

Your numbers 1, 3, 2, 0 are SOH, ETX, STX, which are non-printable characters.

Try the numbers 65, 66 for example, they are letters.

CodePudding user response:

The code shown is not giving you any output as it will not compile.

It is hard to say what you want to archive but here you have an example:

int main(void)
{
    int number[] = {1,3,2,0};
    char c[sizeof(number) / sizeof(number[0])   1] = {0,};
    char d[sizeof(number) / sizeof(number[0])][10];

    for(int i = 0 ; i < 4; i    ){
        c[i] = number[i] % 10   '0';
        snprintf(d[i], 10, "%d", number[i]);
    }
    printf("%s\n", c);

    for(int i = 0 ; i < 4; i    ){
        printf("%s\n",d[i]);
    }

}
  • Related