[Effective-cpp] Item 2: The String Formatters of Manor Farm, Part 1: sprintf

Terje Slettebø tslettebo at broadpark.no
Fri Oct 29 17:46:42 EDT 2004


>From: "White Wolf" <wolof at freemail.hu>

> So I disagree that it is easy to use for the masses.  The easiness comes
> only with practice which can be true for any tool.  It looks simple once
it
> is written, more simple than stream output, since the text remains at one
> place (the format string) so it is more readable what you want to say.
With
> iostreams the text gets scattered.

With something like Boost.Format
(http://www.boost.org/libs/format/index.html), you can get both the
advantage of a format string, and, unlike (s)printf, type safety, works with
any type having an output stream operator defined, and being generic (even
though the syntax may seem a little odd). You can also "reuse" an argument
several times in the format string:

std::cout << boost::format("%1% + %2% = %3%") % 10 % 20 % (10+20) << "\n";
// Prints "10 + 20 = 30"

(Yes, peddling Boost, again. ;) )

Regards,

Terje




More information about the Effective-cpp mailing list