Default Stream Objects in C++ - dummies

Default Stream Objects in C++

By Stephen R. Davis

C++ adds a chunk of code to the front of your program that executes before main() gets control. Among other things, this code creates the default input/output objects shown in this table.

Standard Stream I/O Objects
Object Class Purpose
cin istream Standard char input
wcin wistream Standard wchar_t “wide
char” input
cout ostream Standard char output
wcout wostream Standard wchar_t “wide
char” output
cerr ostream Standard error output
wcerr wostream Standard error wchar_t “wide
char” output
clog ostream Standard log
wclog ostream Standard wchar_t “wide
char” log

You’ve probably seen cin and cout as they read input from the keyboard and output to the display, respectively. The user can reroute standard input and standard output to a file when he executes a program as follows:

C:>MyProgram <InputFile.txt >DefaultOut.txt

Here the operator is saying “Execute MyProgram but read standard input from InputFile.txt instead of the keyboard and send what would otherwise go to the standard output to the file DefaultOut.txt.

Rerouting input and output works from the DOS prompt in Windows and under all versions of Unix and Linux. It’s the easiest way to perform file input/output when you’re trying to write something quick and dirty.

By default, the cerr object outputs to the display just like cout, except it is rerouted separately — rerouting cout-type default output to a file does not reroute cerr output. This allows a program to display error messages to the operator even if cout has been rerouted to a file.

Error messages should be sent to cerr rather than cout just in case the operator has rerouted standard output.

The wcin, wcout, and wcerr are wide version of standard input, output, and error, respectively. These are designed to handle Unicode symbols:

cout  << "This is narrow output" << endl;
wcout << L"This is wide output"  << endl;