用变量写char

时间:2016-04-04 19:22:53

标签: c

让我们说我有:

printf("Hello, my name is %s\n", name_variable);

我想保存printf在char数组中生成的字符串,以便我可以write在某处。这样做的一个解决方案是声明char数组,然后在其上使用strcpystrcat。我想知道是否有一种更优雅的方式。

2 个答案:

答案 0 :(得分:3)

  

我想保存printf在char中生成的字符串

你的意思是/mnt数组?

您可以使用snprintf

char

答案 1 :(得分:1)

请查看[snprintf](http://www.cplusplus.com/reference/cstdio/snprintf/]

此函数能够将值存储在字符串

代码如此:

char s[1024]; // or some other suitable value

snprintf(s, 1024, "Hello, my name is %s\n", name_variable);

printf("Here it is %s\n", s);