I tried researching the difference between cout
, cerr
and clog
on the internet but couldn\'t find a perfect answer. I still am not cle
From a draft C++17 standard document:
30.4.3 Narrow stream objects [narrow.stream.objects]
istream cin;
1 The object
cin
controls input from a stream buffer associated with the objectstdin
, declared in(30.11.1).
2 After the object
cin
is initialized,cin.tie()
returns&cout
. Its state is otherwise the same as required forbasic_ios
(30.5.5.2).::init
ostream cout;
3 The object
cout
controls output to a stream buffer associated with the objectstdout
, declared in(30.11.1).
ostream cerr;
4 The object
cerr
controls output to a stream buffer associated with the objectstderr
, declared in(30.11.1).
5 After the object
cerr
is initialized,cerr.flags() & unitbuf
is nonzero andcerr.tie()
returns&cout
. Its state is otherwise the same as required forbasic_ios
(30.5.5.2).::init
ostream clog;
6 The object
clog
controls output to a stream buffer associated with the objectstderr
, declared in(30.11.1).
cout
writes to stdout
; cerr
and clog
to stderr
Standard Out (stdout
) is intended to receive non-error, non-diagnostic output from the program, such as output from successful processing that can be displayed to the end-user or streamed into some further processing stage.
Standard Error (stderr
) is intended for diagnostic output, such as warning and error messages that indicate the program hasn't or may not have produced the output the user might expect. This input may be displayed to the end user even if the output data is piped to a further processing stage.
cin
and cerr
are tied to cout
They both flush cout
before handling I/O operations themselves. This ensures prompts sent to cout
are visible before the program blocks to read input from cin
, and that earlier output to cout
is flushed before writing an error through cerr
, which keeps the messages in chronological order of their generation when both are directed to the same terminal/file/etc..
This contrasts with clog
- if you write there it won't be buffered and isn't tied to anything, so it will buffer decent sized amounts of logging before flushing. This yields the highest throughput of messages, but means the messages may not be quickly visible to a would-be consumer reading the terminal or tailing the log.