c++iostreamcoutclog

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


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.


Solution

  • 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.