The differences between cerr and cout in C++

  • 2020-05-30 20:46:03
  • OfStack

The differences between cerr and cout in C++

Preface:

cerrThe object controls unbuffered insertions to the standard error output as a byte stream. Once the object is nstructed, the expression cerr.flags & unitbuf is nonzero.

Example


 // iostream_cerr.cpp
// compile with: /EHsc
// By default, cerr and clog are the same as cout
#include <iostream>
#include <fstream>
 
using namespace std;
 
void TestWide( ) 
{
 int i = 0;
 wcout << L"Enter a number: ";
 wcin >> i;
 wcerr << L"test for wcerr" << endl;
 wclog << L"test for wclog" << endl; 
}
 
int main( ) 
{
 int i = 0;
 cout << "Enter a number: ";
 cin >> i;
 cerr << "test for cerr" << endl;
 clog << "test for clog" << endl;
 TestWide( );
}
 
 

 Input 
 Sample Output 
Enter a number: 3
test for cerr
test for clog
Enter a number: 1
test for wcerr
test for wclogcout
 
The object controls insertions to the standard output as a byte stream.
 
cerr 
extern ostream cerr; 
The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags() & unitbuf is nonzero. 
 
cout 
extern ostream cout; 
The object controls insertions to the standard output as a byte stream.
 

cerr: error output stream, unbuffered, cannot be redirected. The output data is placed directly into the specified target without passing through the buffer. Since it does not pass through the buffer, other programs cannot send the output to other targets, so it cannot be redirected.

cout: standard output stream, buffered, redirected. Put the output data into the buffer first, and then from the buffer to the device you specify. When an endl is inserted into an cout stream, all data in the stream is output immediately, regardless of whether the buffer is overflowing, and a newline character is inserted.

Note: the output of cerr can be indirectly redirected with standard error output under Linux

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: