Rodrigo
Rodrigo

Reputation: 12714

How to store the resulting formatted C string

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

Upvotes: 6

Views: 16355

Answers (4)

ThiefMaster
ThiefMaster

Reputation: 318808

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.

Upvotes: 20

Pablo Maurin
Pablo Maurin

Reputation: 1490

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

Upvotes: 2

KevinA
KevinA

Reputation: 629

You would need to use something like sprintf http://www.rohitab.com/discuss/topic/11505-sprintf-tutorial-in-c/

it's used basically like this (remember to malloc the msg variable first)

char* msg;
int ret = sprintf(msg,"My number is %i",10);
printf(msg);

Upvotes: 0

ouah
ouah

Reputation: 145919

Use sprintf:

int n=10
char *msg ="My number is %i";
char bla[32];   // Use an array which is large enough 
sprintf(bla, msg, n);

Upvotes: 0

Related Questions