我很感兴趣(出于各种原因)使用 sprintf 将结果格式化为 std::string
对象。我想出的最直接的语法方式是:
char* buf;
sprintf(buf, ...);
std::string s(buf);
还有其他想法吗?
最佳答案
不要使用 printf
函数行在 C++ 中进行格式化。使用类型安全且不需要用户提供特殊格式字符的流(在本例中为字符串流)的语言特性。
如果你真的想这样做,你可以在你的字符串中预先分配足够的空间,然后调整它的大小,尽管我不确定这是否比使用临时字符缓冲区数组更有效:
std::string foo;
foo.resize(max_length);
int num_bytes = snprintf(&foo[0], max_length, ...);
if(num_bytes < max_length)
{
foo.resize(num_bytes);
}
关于c++ - sprintf 直接转换为 std::string?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8749163/