Boost logo

Boost :

From: Giovanni Bajo (giovannibajo_at_[hidden])
Date: 2002-05-12 13:15:32


The standard C++ library misses formatting capabilities (ala sprintf) in
std::string. It's a very common request on clc++m, because sprintf()-like
syntax to format strings is very popular. The only alternative seems to be
using a stringstream to format through streams, and then copy the output
into a std::string; this works, but the result is a more verbose code, and
also most people (like me) don't like streams to format for several reasons
(see below).

What I am proposing here is an 'extension' to std::string to add formatting
capabilities ala-sprintf, but in a type-safe, no-ellipsis manner. The credit
for this idea goes to Trolltech (QString in the Qt package): When I
discovered this feature last year, I found it so exciting that I immediatly
reimplemented it into a std::string-friendly library, to be used in programs
where Qt is not linked (then, I hardly used it one or two times, but this is
another story ;). A quick example:

cout << mystring("Hello, my name is %1 and I am %2 years
old").arg("Giovanni").arg(999) << endl;

Benefits over sprintf():
- Typesafe. The type of the argument is not specified within the placeholder
(%1 instead of %d,%s or whatever), but it's deduced automatically when it is
- Easier to learn. No need to remember "%-2.3f" funky syntax, just use
arg(floatnumber, 2, 3, align_right) or similar
- Easier to localize: translators can change placeholder order during
translation if required by grammar rules, and the code does not need to be
touched (I learnt this the hard way).

Benefits over streams:
- More readable: you will agree that splitting the string into several
mini-strings with << in the middle is not so readable.
- Way easier to localize: you don't have billions of little strings to put
in your resource-only files, and the translator won't go crazy trying to
re-construct the sentence from little pieces.
- No named temporary stringstream object to be created (unless you think of
"(ostringstream() << var).str()" which is awful IMO).

If there is interest in such a library, I can boostifize (as far as I can)
and submit it.

Giovanni Bajo

Boost list run by bdawes at, gregod at, cpdaniel at, john at