gpt4 book ai didi

c++ - snprintf的使用

转载 作者:行者123 更新时间:2023-11-28 01:55:59 24 4
gpt4 key购买 nike

这不可能吗?当我删除 d[%s] 时,没问题。能解释一下原因吗?

std::string toString() const {
char buf[1024];
int a, b, c;
std::string d;
snprintf(buf, 1024, "a[%d] b[%d]" "c[%d] d[%s]", a, b, c, d);
return buf;
}

最佳答案

snprintf不适用于 std::string%s 修饰符指定如下:

The argument must be a pointer to the initial element of an array of characters. [...]

您需要传递一个以 null 结尾的字符数组。幸运的是,您可以使用 c_strstd::string 获取这样的指针。

只需将您的代码更改为:

snprintf(buf, 1024, "a[%d] b[%d]" "c[%d] d[%s]", a, b, c, d.c_str());

关于c++ - snprintf的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com