Input and Output in C++

Output in C++:
Output in C Plus Plus (C++) is enabled by the object cout (pronounced as “C out”) which is predefined to corresponding to the standard output stream. A stream is an abstraction that refers to a flow of data. The standard output stream normally flows to the screen display, although it can be redirected to other output devices.

cout, when combined with insertion or put-to operator << enables the output in C++ programs. << operator redirects the contents of the variable on its (<<‘s) right to the object on its(<<‘s) left.

A simple example of output of a phrase is depicted below:

cout << " is the best C++ programming tutorial site";

Above statement causes the phrase in the quotation marks to be displayed on the screen.

Input in C++
Contrary to cout, to receive input through the keyboard what is used is object cin (pronounced as “C in”). cin is a object predefined in C++ to correspond to the standard input stream. This stream represents the data coming from the keyboard (unless it has been redirected).

cin, when combined with extraction or get-from operator >> enables the input in C++ programs. >> operators takes the value from the object on its (>>‘s) left and places it in the variables on its right.

A simple example of input of the value of a single variable is depicted below:

cin >> n;

Above statement causes the value provided from the keyboard to get assigned to the variable n.

Cascading of Input and Output in C++
Cascading of input and output is also possible in C++, Let us illustrate this with the following examples:

Example depicting cascading of Input
Suppose we want to read the values from the variables n1, n2 and n3. We can do this with the single statement:

cin >> n1 >> n2 >> n3;

Above one statement is equivalent to the following three statements:

cin >> n1;
cin >> n2;
cin >> n3;

Example depicting cascading of Output
Suppose we want to print the values of the variables n1 and n2. We can do this with the single statement:

cout << "n1 = " << n1 << "n2 = " << n2;

Above one statement is equivalent to the following four statements:

cout << "n1 = ";
cout << n1;
cout << "n2 = ";
cout << n2;

A Special Mention of Header File required for Input and Output in C++
To enable the use of cout,<<,cin and >>, one needs to include a header file named iostream.h in the first line of every program, by the statement:

#include <iostream.h>

This header file contains the declaration that are needed by cout & cin objects and << & >> operators. Without this declaration, the compiler won’t recognize cout & cin and will think << & >> are being used incorrectly in the program.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *