samsamara
samsamara

Reputation: 4750

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

Upvotes: 3

Views: 11903

Answers (2)

owacoder
owacoder

Reputation: 4873

Change

strcpy(finstr,astr);
strcpy(finstr, ":");
strcpy(finstr, bstr);

to

strcpy(finstr,astr);
strcat(finstr, ":");
strcat(finstr, bstr);

You are overwriting the result string with each successive call. You should instead concatenate to the end of the string, using strcat. Although this can just as easily be done with a single sprintf call.

Upvotes: 3

fluter
fluter

Reputation: 13786

You can just do it with one sprintf:

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

Upvotes: 9

Related Questions