This is a newbie question. To create a formatted C string, I use printf
, like:
int n = 10;
printf("My number is %i", 10);
But, how about:
int n = 10
char *msg = "My number is %i", 10;
printf(msg);
How can I store the resulting formatted string in a variable? I want "My number is 10".
You want to use snprintf()
:
int n = 10;
char bla[32]; // Use an array which is large enough
snprintf(bla, sizeof(bla), "My number is %i", n);
Do not use sprintf()
; it is similar to snprintf
but does not perform any buffer size checking so it is considered a security hole - of course you might always allocate enough memory but you might forget to it at some point and thus open a huge security hole.
If you want the function to allocate memory for you, you can use asprintf()
instead:
int n = 10;
char *bla;
asprintf(&bla, "My number is %i", n);
// do something with bla
free(bla); // release the memory allocated by asprintf.
You are looking for sprintf().
int ret;
int n=10;
char msg[50]; /* allocate some space for string */
/* Creates string like printf, but stores in msg */
ret = sprintf(msg,"My number is %i",n);
printf(msg);
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