How to Print
beginner
c++11
In C++ printing is done with the std::cout
object and the left shift operator (<<
).
#include <iostream> int main() { std::cout << "Hello, World!\n"; }
Hello, World!
You can chain multiple objects together of different types:
#include <iostream> int main() { std::cout << "Mars is " << 1.5 << "AU from the Sun.\n"; }
Mars is 1.5AU from the Sun.
Printing Custom Types
By default, C++ will not know how to print the types you define.
To tell C++ how to print your types you overload the left shift operator(<<
) of std::ostream
.
#include <iostream> struct Point { float x, y, z; }; std::ostream& operator<<(std::ostream& o, const Point& p) { o << p.x << ", " << p.y << ", " << p.z; return o; } int main() { Point p{1.0f, 2.0f, 3.0f}; std::cout << p << "\n"; }
1, 2, 3
Just print()
It’s possible to have a more comfortable to use print function in C++. Click here to see how.
Priting std
Containers
C++’s standard library containers do not come with printing capability. In order to print a std::vector
or a std::map
we need to write our own printing function. Click here to see how.