Just print()
advanced
c++17
Related: How to Print in C++
It’s possible to have a more comfortable to use print function in C++. We’ll write a function template to do it. The following function takes any number of arguments of any type and passes them, in order, to std::cout
‘s left shift operator(<<
).
#include <iostream> template <typename ...Args> void print(const Args& ...args) { (std::cout << ... << args); } int main() { print("Mars is ", 1.5, "AU from the Sun.\n"); }
Mars is 1.5AU from the Sun.
println
If we want a “print line” function that always appends a newline character (\n
) after every print that is very easy as well:
#include <iostream> template <typename ...Args> void println(const Args& ...args) { (std::cout << ... << args) << "\n"; } int main() { println("Venus is ", 0.7, "AU from the Sun."); println("Mars is ", 1.5, "AU from the Sun."); }
Venus is 0.7AU from the Sun. Mars is 1.5AU from the Sun.