views:

114

answers:

2

if I want to construct a const char * out of several primitive type arguments, is there a way to build the string using a similar to the printf?

+2  A: 

You can use sprintf, which is exactly like printf except the first parameter is a buffer where the string will be placed.

Example:

char buffer[256];
sprintf(buffer, "Hello, %s!\n", "Beta");
beta
i think you mean sprintf, fprintf prints to files
yjerem
Also, use `snprintf` rather than `sprintf`.
dreamlax
ah yes. as far as I recall, fprintf takes a `fd` not an actual pointer.
piggles
whoops... sorry.
beta
@Mechko: `fprintf` takes a `FILE*`, not a file descriptor, although you can obtain a `FILE*` from a file descriptor easily enough by calling `fdopen`.
dreamlax
+8  A: 

You're probably looking for snprintf.

int snprintf(char *str, size_t size, const char *format, ...);

A simple example:

char buffer[100];
int value = 42;
int nchars = snprintf(buffer, 100, "The answer is %d", value);
printf("%s\n", buffer);
/* outputs: The answer is 42 */

GNU has an example too.

Just to add, you don't actually need to use snprintf - you can use the plain old sprintf (without the size argument) but then it is more difficult to ensure only n characters are written to the buffer. GNU also has a nice function, asprintf which will allocate the buffer for you.

Nick Presta
+1 Neat, that page for `asprintf` led to the [Obstack](http://www.gnu.org/software/libtool//manual/libc/Obstacks.html) documentation, which looks pretty useful in some situations.
Greg Hewgill