What are cin, cout and cerr streams in C++?


cin, cout, cerr, and clog are streams that handle standard inputs and standard outputs. These are stream objects defined in iostream header file.

std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.

std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog).

The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>. It is used for outputting error to the standard output stream.

Note − All the objects declared in this header share a peculiar property - you can assume they are constructed before any static objects you define, in a translation unit that includes <iostream>. Equally, you can assume that these objects are not destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination.

You can use these stream objects as follows −

Example

#include<iostream>
int main() {
   int my_int;
   std::cin >> my_int;
   std::cout << my_int;
   std::cerr << "An error message";
   return 0;
}

Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −

$ g++ hello.cpp

Run it using −

$ ./a.out

Output

If you give it the input 15, this will give the output −

15 An error message

Updated on: 11-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements