Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf to std::string directly?

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?

like image 699
chriskirk Avatar asked Sep 06 '25 03:09

chriskirk


2 Answers

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);
}
like image 115
Mark B Avatar answered Sep 08 '25 12:09

Mark B


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.

like image 30
Xavier V. Avatar answered Sep 08 '25 12:09

Xavier V.