C++ Output(cout) and Input(cin)


Input/Output Library Header Files

There are following header files important to C++ programs:

Header File Function and Description
<iostream> This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.
<iomanip> This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and ssetprecision.
<fstream> This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.

The standard output stream (cout)

The predefined object cout is an instance of iostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen.

The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs.

#include <iostream>
using namespace std;
int  main()
{
   char str[] = "C++ tutorial";
   cout << "Value of str is : " << str << endl;
}
Output
Value of str is : C++ tutorial

The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value.

The << operator is overloaded to output data items of built-in types integer,float,double,strings and pointer values.

The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.


The standard input stream (cin)

The predefined object cin is an instance of iostream class.

The cin object is said to be attached to the standard input device, which usually is the keyboard.

The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs .

Example

#include <iostream>
using namespace std;
int  main ()
{
   char name[100];
   cout << "Please enter your name:";
   cin >> name;
   cout,  <<  "Your name is:"  << name  << endl ;
}

When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the result something as follows:

Output
Please enter your name: Fastest
Your name is: fastest

Share this article on