Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the resulting formatted C string

Tags:

c

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".

like image 459
Rodrigo Avatar asked Nov 30 '22 06:11

Rodrigo


2 Answers

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.
like image 68
ThiefMaster Avatar answered Dec 02 '22 20:12

ThiefMaster


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);
like image 33
Pablo Maurin Avatar answered Dec 02 '22 19:12

Pablo Maurin