Search code examples
ccharintconcatenationstring-concatenation

concatenate two integers into a char * in C


Having forgotten my C knowledge now, having a really hard time figuring out how to do the following:

int a = 5; //getting value from a function
int b = 1; //from a function

what I want to have is:

char * returnstring = "5:1"; //want to return this

I have tried the following but it doesn't work.

    char astr[5], bstr[5];
    sprintf( astr, "%d", a);
    sprintf( bstr, "%d", b);

    char finstr[100]; //final string
    strcpy(finstr, astr);
    strcpy(finstr, ":");
    strcpy(finstr, bstr);

    printf ("%s", finstr);

Solution

  • You can just do it with one sprintf:

    char str[100];
    sprintf(str, "%d:%d", a, b);