When to use cerr and when cout in C ++?

I'm looking for an example that distinguishes between cerr and cout in C ++?

When do I need to use cerr ?

+6
source share
3 answers

Many operating systems allow you to redirect input and output from / to files. When end users redirect your output to a file, end users do not see anything you write to cout ; if you want your output to be viewed by end users, you need a separate thread into which you print messages for them.

Suppose you write a program that reads from standard input in turn and writes these lines to standard output in sorted order. Say your program accepts a command line parameter that says the output should be sorted in ascending or descending order. If end users pass an invalid value for this parameter, you want to print the message "Invalid flag" on the console. Printing it before cout would be wrong because cout could be redirected to a file so that users would not see it. The correct solution in this situation is to write this message to cerr .

+6
source

Quite often, the user of your program is only interested in the results, because they are printed in stdout, for example, if you use the cat unix command, for example:

 $ cat file.txt 

The contents of file.txt are expected to appear on a standard disk. However, if something happens during the execution of the cat (strictly theoretically, nothing occurred to me), you expect it to go to stderr, so as a user, you can still separate the two, for example

 $ cat file.txt 1>result.txt 2>stderr.txt 

Suppose I want to collect the contents of several files, I do the following

 $ cat *.java 1>all_files_conent.java 2>errors.txt 

If any of the files is unavailable (for example, due to permissions), the errors.txt file will have the corresponding message:

 cat: Controller.java: Permission denied 

But the contents of all_files_content.java is as correct as it can be.

Therefore, if the message is the actual product of your program, you should use cout, if it is just a status message, use cerr. Of course, all this does not matter if what goes to the console is just a by-product. However, you can still allow the user to separate the two, as in the example above.

+6
source

std::cout : regular output (console output)

std::cerr : error output (console error)

Google is your friend :)

+1
source

Source: https://habr.com/ru/post/1203992/


All Articles