Ritwik Bose
Ritwik Bose

Reputation: 6069

String concatenation in C

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?

Upvotes: 3

Views: 314

Answers (2)

beta
beta

Reputation: 647

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

Upvotes: 2

Nick Presta
Nick Presta

Reputation: 28665

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.

Upvotes: 8

Related Questions