How to use C++ std::ostream with printf-like formatting?

eonil picture eonil · Feb 27, 2013 · Viewed 67.2k times · Source

I am learning C++. cout is an instance of std::ostream class. How can I print a formatted string with it?

I can still use printf, but I want to learn a proper C++ method which can take advantage of all C++ benefits. I think this should be possible with std::ostream, but I can't find the proper way.

Answer

jogojapan picture jogojapan · Feb 27, 2013

The only thing you can do with std::ostream directly is the well known <<-syntax:

int i = 0;
std::cout << "this is a number: " << i;

And there are various IO manipulators that can be used to influence the formatting, number of digits, etc. of integers, floating point numbers etc.

However, that is not the same as the formatted strings of printf. C++11 does not include any facility that allows you to use string formatting in the same way as it is used with printf (except printf itself, which you can of course use in C++ if you want).

In terms of libraries that provide printf-style functionality, there is boost::format, which enables code such as this (copied from the synopsis):

std::cout << boost::format("writing %1%,  x=%2% : %3%-th try") % "toto" % 40.23 % 50;

Also note that there is a proposal for inclusion of printf-style formatting in a future version of the Standard. If this gets accepted, syntax such as the below may become available:

std::cout << std::putf("this is a number: %d\n",i);