Formatting a string in C

You can usually 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 can I do this? I am looking for something like this.

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

I hope this is clear what I'm looking for ...

+5
source share
5 answers

One of the options is to use it sprintf, which works in exactly the same way as printf, but as the first parameter, it takes a pointer to a buffer in which it should put the resulting string.

It is preferable to use snprintfone that takes an additional parameter containing the length of the buffer to prevent buffer overflows. For example:

char buffer[1024];
snprintf(buffer, 1024, "No record with name %s found\n", inputString);
+31
source

sprintf. :

char output[80];
sprintf(output, "No record with name %s found\n", inputString);

sprintf . , . , sprintf , output, , , . , , — sprintf, - :

char output[10];
sprintf(output, "%s", "This string is too long");

snprintf, :

char output[10];
snprintf(output, sizeof output, "%s", "This string is too long, but will be truncated");

, Windows, _sntprintf, .

+10

(, ), ...printf().

, :)

+7

sprintf (. ).

int n = sprintf(str, "No record with name %s found\n", inputString);
+3

sprintf(str, "No record with name %s found\n", inputString);
+3