当我编译这样的东西时,我会收到警告...
std::string something = "bacon";
sprintf("I love %s a lot", something.c_str());
它说“警告:不建议将字符串常量转换为'char *'。我尝试将文本转换为...
const char *
相反,但是我得到了另一个错误。如果有更好的选择,我不致力于sprintf。
最佳答案
sprintf("I love %s a lot", something.c_str);
在该代码中,应使用正确的函数调用
something.c_str()
语法来调用()
。还要注意,上面的
sprintf()
用法是错误的,因为您没有为生成的格式化字符串提供有效的目标字符串缓冲区。此外,出于安全原因,您应该使用更安全的
snprintf()
而不是sprintf()
。实际上,使用snprintf()
可以指定目标缓冲区的大小,以避免缓冲区溢出。以下可编译代码是
snprintf()
用法的示例:#include <stdio.h>
#include <string>
int main()
{
std::string something = "bacon";
char buf[128];
snprintf(buf, sizeof(buf), "I love %s a lot", something.c_str());
printf("%s\n", buf);
}
附言
通常,在C ++中,您可以考虑使用
std::string::operator+
进行字符串连接,例如:std::string result = "I love " + something + " a lot";