3

Is there a common function available to be able to do sprintf type String formatting without having to supply a fixed size buffer, that returns a string class instance?

I know about stringstream it doesn't do what I want, I don't want to hard code the position of the tokens in the output statement like it requires.

I want to be able to define a pattern like sprintf lets you, but without the C baggage and in a more idiomatic Object Oriented C++ manner.

Maybe some function that does what sprintf does using a stringstream and produces a string object? Something along the line of the convenience of what String.format() does in Java or the equivalent String formatting syntax in Python.

  • 4
    Can you specifically state what `stringstream` doesn't do that you require? Combining `stringstream` with the various output specifications from ``, there are very few things you can do with `sprintf` that cannot be replicated. – Chad Jul 21 '11 at 18:15
  • See: http://stackoverflow.com/q/119098/14065 – Martin York Jul 21 '11 at 20:22

2 Answers2

10

The Boost Format Library:

The <boost/format.hpp> format class provides printf-like formatting, in a type-safe manner which allows output of user-defined types.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
0

If you don't use Boost.Format or Boost.Locale you can use my simple stringstream wrapper or wrap it even further:

fakeformat

example:

REQUIRE( ff::format("{2}ff{1}").with('a').also_with(7).now()=="7ffa" );

Ideone

Dmitry Ledentsov
  • 3,620
  • 18
  • 28