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.
-- From "Programming/C++ tutorial" by P. Lutus.
I wrote independently but came up with answer similar to user3283405
My solution uses vasprintf() to acheive formatting, and uses operator overloading of << of std::ostream to free the memory in right place.
Usage:
Code:
Note that compiler doesn't check format inside putf(), so compiler flag -Wformat-nonliteral will not warn for suspicious code in putf() and you need to care uncontrolled format string problem by yourself.
Detailed info can be found on GitHub
This is an idiom I have gotten used to. Hopefully it helps:
&
To implement printf one could use c++11 template parameters:
Output
This a very simple code and it can be improved.
1) The advantage is that it uses << to print objects to the stream, so you can put arbitrary arguments that can be output via <<.
2) It ignores the type of the argument in the formatted string: after % can stand arbitrary symbol even a space. The output stream decides how to print the corresponding object. It also compatible with printf.
3) A disadvantage is that it can not print the percent symbol '%', one need to slightly improve the code.
4) It can not print formatted numbers, like %4.5f
5) If the number of arguments is less than predicted by formatted string, then the function just print the rest of the string.
6) If the number of arguments is greater than predicted by formatted string, then the remained arguments are ignored
One can improve the code to make 2)-6) to fully mimic the printf behaviour. However, if you follow the rules of printf, then only 3) and 4) need essentially to be fixed.
Sample output:
Code (with put_printf usage demonstrated in put_timestamp):
Comments about put_printf:
I suggest using ostringstream instead of ostream see following example :
example usage: