0

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.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
  • Note there is [to_string](http://stackoverflow.com/a/21519186/1708801) in C++11. – Shafik Yaghmour Jul 10 '15 at 14:55
  • @ShafikYaghmour While that is very useful, you [cannot fine-tune the exact format](https://stackoverflow.com/questions/13686482/c11-stdto-stringdouble-no-trailing-zeros) of the produced string like you can with format codes. – Cory Kramer Jul 10 '15 at 14:57
  • @CoryKramer sure, I just think it should be mentioned in the question and explained why it is insufficient. – Shafik Yaghmour Jul 10 '15 at 14:58
  • Agreed. If the OP just wants, e.g. `%f` then `std::to_string` is perfect. It just cannot do `%3.5f` for example. – Cory Kramer Jul 10 '15 at 14:59

0 Answers0