PercivallAkihiko
PercivallAkihiko

Reputation: 107

Convert int array to string using C

So I have something like this:

int array[5] = {1, 6, 2, 4, 4};
char string[255];

/*do something*/

printf("%s\n", string);

Output should be:

[1, 6, 2, 4, 4]

I really don't know where to start...

Upvotes: 2

Views: 6767

Answers (3)

chqrlie
chqrlie

Reputation: 144715

To convert the array to a string, you should use snprintf:

#include <stdio.h>

char *join(char *dest, size_t size, const int *array, size_t count) {
    if (size == 0) {
        return NULL;
    }
    if (size == 1) {
       dest[0] = '\0';
       return dest;
    }
    size_t pos = 0;
    dest[pos++] = '[';
    dest[pos] = '\0';
    for (size_t i = 0; pos < size && i < count; i++) { 
        int len = snprintf(dest + pos, size - pos, "%d%s",
                           array[i], (i + 1 < count) ? ", " : "]");
        if (len < 0)
            return NULL;
        pos += len;
    }
    return dest;
}

int main() {
    int array[5] = { 1, 6, 2, 4, 4 };
    char string[255];

    if (join(string, sizeof string, array, sizeof(array) / sizeof(*array))) {
        printf("%s\n", string);
    }
    return 0;
}

Upvotes: -1

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. cleanly compiles
  2. performs the desired functionality
  3. demonstrates the use of strcpy() and sprintf()
  4. avoids the use of 'magic' numbers
  5. lets the compiler calculate the number of entries in the array[]

and now, the proposed code:

#include <stdio.h>
#include <string.h>


int main( void )
{
    int array[] = {1, 6, 2, 4, 4};
    char string[255] = {0};

    /*do something*/
    strcpy( string, "[" );
    for( size_t i = 0; i < (sizeof(array)/sizeof(int)) -1; i++ )
    {
        sprintf( &string[ strlen(string) ],  "%d, ", array[i] );
    }

    sprintf( &string[ strlen(string) ],  "%d", array[4] );
    strcat( string, "]" );

    printf("%s\n", string);
}

a run of the proposed code results in:

[1, 6, 2, 4, 4]

Upvotes: 3

sobin thomas
sobin thomas

Reputation: 59

You need to convert the integer into equivalent char using the ascii table subtraction and then strcat to the main string

Upvotes: -1

Related Questions