Print using stream-based output devices as a type-safe alternative to C's printf. The stream to print to output is std::cout from the iostream library:
#include <iostream>
Variables and literals can be printed to std::cout using the stream insertion operator (<<):
int var = 123;
std::cout << var;
std::cout << 456;
Printing can also be chained:
std::cout << "nums: " << var << ", " << 456 << "\n";
Classes can be printed if the stream insertion operator has been implemented:
class Foo {
public:
int var = 24;
friend std::ostream& operator<<(std::ostream& os,
Foo const& obj) {
os << obj.var;
return os;
}
};
Foo obj;
std::cout << obj;
iostream introduces std::endl which is syntactic-sugar for printing a new line and flushing the buffer:
std::cout << var << std::endl;
Dan