user319895
user319895

Reputation: 21

Storing Formatted Data in C

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

Upvotes: 2

Views: 94

Answers (3)

slacker
slacker

Reputation: 2142

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.

Upvotes: 0

Joe
Joe

Reputation: 42646

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.

Upvotes: 3

Goz
Goz

Reputation: 62333

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!

Upvotes: 1

Related Questions