Reputation: 6069
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
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
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 */
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