String Concatenation in C

if I want to build const char *from several arguments of a primitive type, is there a way to build a string using a similar one printf?

+3
source share
2 answers

You may be looking for snprintf .

int snprintf(char *str, size_t size, const char *format, ...);

A simple example:

char buffer[100];
int value = 42;
int nchars = snprintf(buffer, 100, "The answer is %d", value);
printf("%s\n", buffer);
/* outputs: The answer is 42 */

GNU also has an example .

Just to add, you actually don't need to use it snprintf- you can use the plain old one sprintf(without the size argument), but then it's harder to guarantee that only n characters are written to the buffer, GNU also has a nice function asprintf, which will allocate a buffer for you.

+8
source

sprintf, , printf, , , .

:

char buffer[256];
sprintf(buffer, "Hello, %s!\n", "Beta");
+2

Source: https://habr.com/ru/post/1743110/


All Articles