Error Stream Object in C++ with an example
Hello learners, today in this tutorial we will learn about the Error stream objects in C++. std:: cerr, std:: clog are the error stream objects and they are the instances of an ostream class that is used to print the errors from the program. It is good to use std::cerr to print the errors. Let’s understand this in more detail using an easy and comprehensible example.
Standard error stream(std::cerr): The predefined object cerr is an instance of an ostream class. The cerr object is said to be attached to the standard error device which is the display screen but the object cerr is unbuffered and each stream insertion to cerr causes its output to appear immediately which means it is not buffered in the meantime.
The cerr can be used with the stream insertion operator( << ).
Standard error stream(std::clog): The predefined object clog is an instance of an ostream class. The clog object is said to be attached to the standard error device which is the display screen but the object clog is buffered this means that each insertion to clog could cause its output to be held in a buffer until the buffer is flushed.
The clog can be used with the stream insertion operator( << ).
Let’s see an example for a better understanding:
Here is the code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Something wrong here ";
// This will print in stdout window
cout << "Hello World\n";
// This will print in stderr window
cerr << "Error Message unbuffered : " << s1 ;
// This will print in stderr window
clog << "\nError Message buffered: " << s1 ;
return 0;
}
Output: In stdout window
Hello World
In stderr window
Error Message unbuffered: Something wrong here
Error Message buffered: Something wrong here
Here in std::cerr, the output is unbuffered i.e. why it brings the difference between the std::cout & std::cerr.
Conclusion:
std::cerr -> This is the unbuffered version of the standard error stream.
std::clog -> This is the buffered version of the standard error stream.
std::cout -> This is the buffered version of the standard out stream.
Hope this article was helpful to you. Keep Coding Keep Learning.