[英]concatenating strings and snprintf in c
I'm wondering if this is the proper way to concatenate
and NUL
terminate strings including width. 我想知道这是否是
concatenate
和NUL
终止包含宽度的字符串的正确方法。
#define FOO "foo"
const char *bar = "bar";
int n = 10;
float f = 10.2;
char *s;
int l;
l = snprintf (NULL, 0, "%-6s %-10s %4d %4f",FOO, bar, n, f);
s = malloc (l + 4); // should it be the number of formats tags?
if (s == null) return 1;
sprintf (s, "%-6s %-10s %4d %4f", FOO, bar, n, f);
很少有系统在其标准C库中具有asprintf
函数,该函数完全可以执行您在此处所做的事情:allocate和sprintf
。
You only need to add 1
to the value returned by snprintf()
, since there is only one null terminator added. 您只需要向
snprintf()
返回的值加1
,因为仅添加了一个空终止符。
However, you do need to check for l == -1
(indicating that snprintf()
failed). 但是,您确实需要检查
l == -1
(指示snprintf()
失败)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.