Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a string in C

Tags:

c

Normally you can print a string in C like this..

printf("No record with name %s found\n", inputString);

But I wanted to make a string out of it, how I can do it? I am looking for something like this..

char *str = ("No record with name %s found\n", inputString);

I hope it is clear what I am looking for...

like image 715
itsaboutcode Avatar asked Nov 26 '22 21:11

itsaboutcode


1 Answers

One option would be to use sprintf, which works just like printf but takes as its first parameter a pointer to the buffer into which it should place the resulting string.

It is preferable to use snprintf, which takes an additional parameter containing the length of the buffer to prevent buffer overruns. For example:

char buffer[1024];
snprintf(buffer, 1024, "No record with name %s found\n", inputString);
like image 84
James McNellis Avatar answered Jan 19 '23 21:01

James McNellis