std::cout#include <iostream> writes to standard output. It is a type-safe alternative to C's printf and is available from the iostream header. Variables and literals can be printed to std::cout#include <iostream> using the stream insertion operator (<<):
#include <iostream>
int var = 123;
std::cout#include <iostream> << var;
std::cout#include <iostream> << 456; // 123456Printing can also be chained:
std::cout#include <iostream> << "nums: " << var << ", " << 456 << "\n"; // nums: 123, 456Classes can be printed if the stream insertion operator has been implemented:
class Foo {
public:
Foo() : var(24) {}
int var;
friend std::ostream#include <iostream>& operator<<(std::ostream#include <iostream>& os, const Foo& obj) {
os << obj.var;
return os;
}
};
Foo obj;
std::cout#include <iostream> << obj;std::endl#include <iostream> prints a new line and flushes the buffer:
std::cout#include <iostream> << var << std::endl#include <iostream>;Note
Prefer "\n" over std::endl#include <iostream> unless the output must appear immediately. Flushing on every line is slow.
Dan