What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?

Generally you use std::cout for normal output, std::cerr for errors, and std::clog for "logging" (which can mean whatever you want it to mean).

The major difference is that std::cerr is not buffered like the other two.


In relation to the old C stdout and stderr, std::cout corresponds to stdout, while std::cerr and std::clog both corresponds to stderr (except that std::clog is buffered).


stdout and stderr are different streams, even though they both refer to console output by default. Redirecting (piping) one of them (e.g. program.exe >out.txt) would not affect the other.

Generally, stdout should be used for actual program output, while all information and error messages should be printed to stderr, so that if the user redirects output to a file, information messages are still printed on the screen and not to the output file.


Standard output stream (cout): cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator (<<).

Un-buffered standard error stream (cerr): cerr is the standard error stream which is used to output the errors. This is also an instance of the ostream class. As cerr is un-buffered so it is used when we need to display the error message immediately. It does not have any buffer to store the error message and display later.

Buffered standard error stream (clog): This is also an instance of ostream class and used to display errors but unlike cerr the error is first inserted into a buffer and is stored in the buffer until it is not fully filled.

further reading : basic-input-output-c