How to use C++ std::ostream with printf-like formatting?
Solution 1:
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);
Solution 2:
In C++20 you'll be able to use std::format
for safe printf
-like formatting:
std::cout << std::format("The answer is {}.\n", 42);
In addition to that the {fmt} library, std::format
is based on, provides the print
function that combines formatting and output:
fmt::print("The answer is {}.\n", 42);
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
Solution 3:
This is an idiom I have gotten used to. Hopefully it helps:
// Hacky but idiomatic printf style syntax with c++ <<
#include <cstdlib> // for sprintf
char buf[1024]; sprintf(buf, "%d score and %d years ago", 4, 7);
cout << string(buf) <<endl;
&