I'm interested (for various reasons) format using sprintf with the result in a std::string
object. The most syntactically direct way I came up with is:
char* buf;
sprintf(buf, ...);
std::string s(buf);
Any other ideas?
I'm interested (for various reasons) format using sprintf with the result in a std::string
object. The most syntactically direct way I came up with is:
char* buf;
sprintf(buf, ...);
std::string s(buf);
Any other ideas?
Don't use the printf
line of functions for formatting in C++. Use the language feature of streams (stringstreams in this case) which are type safe and don't require the user to provide special format characters.
If you really really want to do that, you could pre-allocate enough space in your string and then resize it down although I'm not sure if that's more efficient than using a temporary char buffer array:
std::string foo;
foo.resize(max_length);
int num_bytes = snprintf(&foo[0], max_length, ...);
if(num_bytes < max_length)
{
foo.resize(num_bytes);
}
Answered here. To get length of buffer needed, call:
snprintf( nullptr, 0, format, args... )
You can write short function which can be used as such:
std::string s = string_sprintf("%g, %g\n", 1.23, 0.001);
Example in linked stackoverflow answer.
If you absolutely want to use sprintf
, there is no more direct way than the one you wrote.
sprintf Writes into the array pointed by str a C string
If you want to transform this C string
into a std::string
, there is no better and safer way than the one you wrote.