tags:

views:

53

answers:

3

Im trying to add variables to a C char array. Also I have tried sprintf, but it is causing a few other issues within my program.

I am looking to do something like this:

char* age = "My age is = " + age;

I am planning on sending the char array to a socket using send()

+1  A: 

If you can use C++ then just use std::string to get this functionality ...

Under C you just can't do it using operator overloads. "strcat" allows you to concatenate 2 strange. Just make sure you have space to store the resulting string!

Goz
+3  A: 

s(n)printf is really the right answer here. What issues is it causing? Try and fix those issues vs. throwing the right tool away.

Joe
sprintf is always wrong answer. try snprintf :)
kotlinski
Sorry, oversimplified. Yes, unless you KNOW your formatting vs. buffer size, then yes, snprintf is definitely the way to go.
Joe
A: 

Use sprintf(). Remember to allocate a large enough buffer for the array. Like this:

char buf[24];
sprintf(buf, "My age is = %d", age);

24 chars are long enough to contain the result here, whatever the value of age is. I'm assuming that age is a 32-bit integer.

Of course, if you change the text to something longer, you will have to increase the size of the buffer.

slacker