• Home
  • 2.13 std::cerr

2.13 std::cerr

View Categories

2.13 std::cerr

1 min read

Table of Contents

The std::cerr object is the standard error output stream in C++. It is used to display error messages and diagnostic information separately from normal program output. Keeping error messages on a separate stream allows them to be redirected or processed independently.

Unlike std::cout, the std::cerr stream is unbuffered. This means that error messages are written to the output device immediately without waiting for the output buffer to fill.

Source Code #

#include <iostream>

int main()
{
    std::cout << "Program started.\n";

    std::cerr << "Error: Unable to open the file.\n";

    std::cout << "Program terminated.\n";

    return 0;
}

Output #

Program started.
Error: Unable to open the file.
Program terminated.

Explanation #

  • std::cerr is the standard error output stream defined in the <iostream> library.
  • It is primarily used to display error messages, warnings, and diagnostic information.
  • Unlike std::cout, std::cerr is unbuffered, so its output is displayed immediately.
  • Separating normal output (std::cout) from error output (std::cerr) makes it easier to redirect or log each stream independently.
  • The stream insertion operator (<<) is used with std::cerr in the same way as with std::cout.
  • Using std::cerr helps distinguish program errors from regular program output.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *