1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn About Input and Output

By David Bolton, About.com

6 of 8

About clog and cerr

Like cout, clog and cerr are pre-defined objects defined in ostream. The iostream class inherits from both ostream and istream so that's why the cout examples can use iostream.

Buffered and Unbuffered

  • Buffered - All output is temporarily stored in a buffer and then dumped to screen in one go. Both cout and clog are buffered.
  • Unbuffered- All output goes immediately to the output device. An example of an unbuffered object is cerr.
The example below demonstrates that cerr is used in the same way as cout.

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{ cerr.width(15) ;
cerr.right;
cerr << "Error" << endl;
return 0;
}
The main problem with buffering, is if the program crashes then the buffer contents are lost and it's harder to see why it crashed. Unbuffered output is immediate so sprinkling a few lines like this through the code might come in useful.

cerr << "Entering Dangerous function zappit" << endl;

The Logging Problem

Building a log of program events can be a useful way to spot difficult bugs- the type that only occur now and then. If that event is a crash though, you have the problem- do you flush the log to disk after every call so you can see events right up to the crash or keep it in a buffer and periodically flush the buffer and hope you don't lose too much when the crash occurs?

There is an alternative method. Use a 3rd party application to log events. I've put this in a quick tip How to Debug Windows Applications Without a Debugger.

On the next page : Using cin for input

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. About clog and cerr

©2009 About.com, a part of The New York Times Company.

All rights reserved.