What I'm trying to do is make a new char* using a syntax similar to printf:
char* myNewString = XXXXprintf("My string says %s", myFirstString);
Is this doable without printing to an output stream?
You're looking for the sprintf or snprintf function.
Note that sprintf doesn't return a pointer to a newly allocated string; you have to allocate the string yourself, and make sure it's big enough:
char target[100];
sprintf(target, "My string says %s", myFirstString);
Unless you can be certain that the target is big enough, you should use snprintf, which limits the number of bytes copied to the target string.
snprintf returns the number of characters that would have been written to the target string. You can call snprintf with a null target and zero size to find out how many big a buffer is needed, then allocate the buffer and call it again to write to the target (NOTE: My original code sample had an off-by-one error.)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *myFirstString = "hello, world";
char *target;
size_t size = snprintf(NULL, 0, "My string says %s", myFirstString);
target = malloc(size+1); /* +1 for terminating '\0' */
if (target == NULL) {
fprintf(stderr, "Allocation failed\n");
exit(EXIT_FAILURE);
}
size = snprintf(target, size+1, "My string says %s", myFirstString);
printf("target = \"%s\"\n", target);
return 0;
}
Note that snprintf was added to C by the 1999 ISO standard. Microsoft's compiler doesn't appear to support it; it does provide a function it calls _snprintf which probably does the same thing.
There's also a GNU extension called asprintf which does allocate the string for you:
char *target;
asprintf(&target, "My string says %s", myFirstString);
If you use this, you'll have to use free() later to deallocate the string. And since this is a GNU extension, it will make your code less portable.
Sure, this is what sprintf is for: printf style formatting into a provided char*.
This documentation covers sprintf and related printf functions. Be sure to consider using snprintf instead: proper usage will make it a bit safer than sprintf by limiting the number of bytes actually copied to the supplied buffer.
The usage is a little different from your example: you supply a buffer which is modified by the sprintf. The function doesn't return the result, like other printf functions, return an int: the number of characters printed.
char myNewString[MAX_LEN];
snprintf(myNewString, MAX_LEN, "My string says %s", myFirstString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With