在c中连接字符串和snprintf
我想知道这是否是连接
和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);
I'm wondering if this is the proper way to concatenate
and NUL
terminate strings including width.
#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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
相当多的系统在其标准 C 库中都有一个函数
asprintf
,它的功能与您在这里所做的完全一样:分配和sprintf
。Quite a few systems have a function
asprintf
in their standard C libraries that does exactly what you do here: allocate andsprintf
.您只需将
1
添加到snprintf()
返回的值中,因为只添加了一个空终止符。但是,您确实需要检查
l == -1
(表明snprintf()
失败)。You only need to add
1
to the value returned bysnprintf()
, since there is only one null terminator added.However, you do need to check for
l == -1
(indicating thatsnprintf()
failed).