strcpy(buf, "my_id_%d_",i)
strcpy(buf1, "my_com_id_%d", j)

First I want to place value of i into "my_id_1" like so and copy to buf. And do the same thing in second line the code. Now I want to join both buf and buf1 so it will give me a new string "my_id_1_my_com_id_2".

How do you do this kind of stuff and joining two strings in C?

10 Years
Discussion Span
Last Post by ssharish2005

strcpy() is not like printf() that accepts a format specifier as a parameter.
You need to convert the integer into a string before trying to add it to the final buffer.
Search for the function sprintf to do that.


According to the prototype of sprintf:

int sprintf ( char * str, const char * format, ... );

you can.


What you are after is something smilier to this.

char Buffer[20];
int count = 10;

sprintf(Buffer, "my_id_%d_", count);

To be more safer on hand use snprintf, if you are worried about overflow and all. Do the same for your send concatenation.

The above is just an sample code which would give you an idea on how to use sprintf. You will have change the variables to get used in you program.

And to achive what you want, either you will have to call sprintf twice or you will have use the combinaton of strcat and sprintf function calls. Like

sprintf(Buffer, "my_id_%d_", count);
 count += 10;
 sprintf(FinalStr, "%smy_com_id_%d", Buffer, count);


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.