What is the difference between cerr and cout streams in c++?



cout is an object of the stdout stream, while cerr is an object of the stderr stream.
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. These are both provided by the <iostream> library in C++.

In this article, we will learn the difference between these two output streams in more detail.

Character Output Stream (cout)

The character output stream is used to display the data or information to the console (standard output device, basically the screen), like printing messages, results, or program status. By default, it is buffered, which means the data will first be stored in an internal memory area known as a buffer. This buffer holds the data until it gets full or is forced to be printed with an explicit command. Explicit commands like std::endl or std::flush.

Syntax

Here is the following syntax for cout in C++.

std::cout << data;

Example

#include <iostream> 
using namespace std; 

int main() {
    // Printing a string
    cout << "Hello, TutorialsPoint Learner!" << endl;

    // Printing an integer
    int number = 10;
    cout << "The value of number is: " << number << endl;

    return 0;
}

Output

Hello, TutorialsPoint Learner!
The value of number is: 10

In the code above, we can see how we have displayed the output on the screen using cout.

Character error output stream (cerr)

The cerr (character error) is an output stream, which is used to display error messages or diagnostic information to the console (standard output device, basically the screen). Unlike cout, cerr is not buffered, therefore, it displays output immediately without waiting to fill up a buffer.

Syntax

Here is the following syntax for cerr in C++.

cerr << expression << [more expressions] << ... ;

Example

#include <iostream>
using namespace std;

int main() {
    int number = -3;

    if (number < 0) {
        cerr << "Error: Negative number!" << endl;
    } else {
        cout << "Number is: " << number << endl;
    }

    return 0;
}

Output

ERROR!
Error: Negative number!

Generally, stdout is used for actual program output, whereas all information and error messages should be printed to stderr, in order that if the user redirects output to a file, information messages are still printed on the screen and not to the output file.

Akansha Kumari
Akansha Kumari

Hi, I am Akansha, a Technical Content Engineer with a passion for simplifying complex tech concepts.

Updated on: 2025-05-02T18:48:58+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements