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

后端 未结 7 1524
小蘑菇
小蘑菇 2020-12-07 08:32

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

7条回答
  •  -上瘾入骨i
    2020-12-07 08:51

    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 object stdin, declared in (30.11.1).

    2 After the object cin is initialized, cin.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (30.5.5.2).

    ostream cout;

    3 The object cout controls output to a stream buffer associated with the object stdout, declared in (30.11.1).

    ostream cerr;

    4 The object cerr controls output to a stream buffer associated with the object stderr, declared in (30.11.1).

    5 After the object cerr is initialized, cerr.flags() & unitbuf is nonzero and cerr.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (30.5.5.2).

    ostream clog;

    6 The object clog controls output to a stream buffer associated with the object stderr, declared in (30.11.1).

    Discussion...

    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.

提交回复
热议问题