I am looking for an example that differentiates between cerr
and cout
in C++?
When do I need to use cerr
?
I am looking for an example that differentiates between cerr
and cout
in C++?
When do I need to use cerr
?
Quite often the user of your program is interested only in results, because these are printed to stdout, for instance, if you use a unix command cat, eg:
$ cat file.txt
You're expecting file.txt contents to appear on stdout. However, if anything happens during the execution of cat (strictly theoretically speaking, nothing has ever happenned to me), you'd expect it to go to stderr, thus, as a user, you're still able to separate the two, eg:
$ cat file.txt 1>result.txt 2>stderr.txt
Suppose I want to collect contents of multiple files, I do the following
$ cat *.java 1>all_files_conent.java 2>errors.txt
In case any of the files isn't accessible (eg. because of permissions), errors.txt will have appropriate message:
cat: Controller.java: Permission denied
But the contents of all_files_content.java are as correct as they can be.
Therefore, if the message is an actual product of your program, you should use cout, if it's just a status message, use cerr. Of course, all this doesn't matter that much if what goes to the console is just a byproduct. However, you might still want to allow user to separate the two, as in the example above.
Many operating systems let you redirect input and output from/to files. When end-users redirect your output to a file, end-users do not see anything that you write to cout
; if you want your output to be seen by end-users, you need a separate stream to which you print messages for them.
Suppose you are writing a program that reads from the standard input line-by-line, and writes these lines to the standard output in sorted order. Let's say that your program takes a command-line parameter that says if the output needs to be sorted in ascending or descending order. If end-users pass an invalid value for this parameter, you want to print a message "Invalid flag"
to the console. Printing it to cout
would be incorrect, because cout
could be redirected to a file, so the users would not see it. The correct solution in this situation is to write this message to cerr
.
std::cout
: Regular output (console output)
std::cerr
: Error output (console error)
Google is your friend :)
You can refer to this answer under another question here. The major difference is std::cerr
is not buffered and is usually used to display an error. But I've also seen many people use std::cerr
to output anything you want to immediately see (you don't want it to be buffered), even if it's not an error message.
© 2022 - 2024 — McMap. All rights reserved.