开发者

String concatenation in C

if I want to construct a const char * out of several primitive type arguments, is there a way to build the开发者_Go百科 string using a similar to the printf?


You're probably 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 has an example too.

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


You can use sprintf, which is exactly like printf except the first parameter is a buffer where the string will be placed.

Example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜