In plain C, we can use sprintf
to write a formatted string to a preallocated char array. But it has limitations, the most obvious being the need to preallocate a sufficiently large array in advance when you don't always know how long the output will be.
How can we use C-style formatting to create an std::string
in C++? I'd like to be able to do something like:
int x = 10;
std:: string s = astringprintf("pi*%d = %8.3f", x, M_PI*x);
Ideally, warnings would be given if the formats don't match the types given - just as g++
(and clang++
?) give if you mess up your call to printf
.