I tried researching the difference between cout
, cerr
and clog
on the internet but couldn't find a perfect answer. I still am not clear on when to use which. Can anyone explain to me, through simple programs and illustrate a perfect situation on when to use which one?
I visited this site which shows a small program on cerr
and clog
, but the output obtained over there can also be obtained using cout
. So, I'm confused over each one's exact use.
stdout
andstderr
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 tostderr
, so that if the user redirects output to a file, information messages are still printed on the screen and not to the output file.Both cout and clog are buffered but cerr is un-buffered and all of these are predefined objects which are instances of class ostream. The basic use of these three are cout is used for standard input whereas clog and cerr is used for showing errors. The main point why cerr is un-buffered is may be because suppose you have several outputs in the buffer and an error exception is mentioned in the code then you need to display that error immediately which can be done by cerr effectively.
Please correct me if I am wrong.
cout is usually used to display some statements on user screen. ex- : cout<<"Arlene Batada";
output:
Arlene Batada
cerr does not require a buffer, so it is faster than the other ones and does not use the memory that cout uses, but because cout is buffered, it's more useful in some cases. So:
The difference of these 3 streams is buffering.
Please check the following code, and run DEBUG through 3 lines: f(std::clog), f(std::cerr), f(std::out), then open 3 output files to see what happened. You can swap these 3 lines to see what will happen.
Generally you use
std::cout
for normal output,std::cerr
for errors, andstd::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
andstderr
,std::cout
corresponds tostdout
, whilestd::cerr
andstd::clog
both corresponds tostderr
(except thatstd::clog
is buffered).