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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With