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::cerris 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::cerris 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 withstd::cerrin the same way as withstd::cout. - Using
std::cerrhelps distinguish program errors from regular program output. return 0;terminates the program successfully.