What cout is
cout is the standard output stream in C++. It is an object declared in the <iostream> header, and its name is in the std namespace, so the full name is std::cout. It sends data to standard output, which is usually the screen.
You use it with the << operator:
#include <iostream>
int main() {
std::cout << "This text goes to standard output.\n";
return 0;
}
The output is:
This text goes to standard output.
What a stream is
A stream is a sequence of data that moves in one direction between a program and something else, such as the screen, a file or the keyboard. An output stream carries data out of the program. cout is the output stream that usually goes to the terminal. Its input counterpart is cin, which carries data into the program. For reading input, see c input string.
An object, not a function
cout is an object, so you do not call it with parentheses. You apply << to it instead. Its type is std::ostream, the standard class for output streams.
Standard output and standard error
Standard output is where a program’s normal results go. Standard error is a separate place for error messages. C++ provides std::cerr for standard error:
#include <iostream>
int main() {
std::cout << "Result: 42\n";
std::cerr << "Warning: example message\n";
return 0;
}
If you run this program with its output sent to a file, such as ./program > output.txt in most shells, the cout text goes into the file and the cerr text still appears on the screen.
C++ also has std::clog, which is meant for log messages and is buffered, unlike std::cerr.
Buffering
cout does not always write each piece of output right away. It often collects text in a buffer and writes it in larger chunks. This is usually invisible, but it can matter. If a program stops unexpectedly, text still in the buffer may not appear. Writing std::endl or calling std::cout.flush() pushes the buffered text out. By contrast, std::cerr normally flushes right away.
Using it in practice
Many beginner programs print with cout. For step-by-step printing examples, including formatting, see c cout.
Quick recap
coutis C++’s standard output stream.- It is declared in
<iostream>and its name lives in thestdnamespace. - You send data to it with
<<. cerris for error messages.- Output may sit in a buffer until it is flushed.