Use Of I/O Operators

In C++, input and output (I/O) operators are used to facilitate input from the user and output to the console. The input operator or extraction operator >> is used with the standard input stream cin, while the output operator or insertion operator << is used with the standard output stream cout.

Input Operator

The input operator >> extracts data from the standard input stream cin and stores it into variables in the program. It treats data as a stream of characters and facilitates the flow of these characters from cin into the program.

Example Of Input Operator
#include<iostream>
using namespace std;
 
int main () {
  int a;
  cin>>a;
 
  a = a+1;
 
  return 0;
}

In this example, the statement cin>>a takes an input from the user and stores it in the variable a.

Output Operator

The output operator << inserts data into the standard output stream cout for display to the user. It treats data as a stream of characters and directs these characters from the program to cout for output.

Example Of Output Operator
#include<iostream>
using namespace std;
 
int main () {
  int a;
  cin>>a;
 
  a=a+1;
 
  cout<<a;
 
  return 0;
}

In this example, the statement cout<<a displays the value of variable a.

Cascading Of I/O Operators

Cascading of input and output operators refers to the consecutive occurrence of these operators in a single statement. This allows multiple input or output operations to be performed in a single line of code, enhancing readability and reducing code size.

A program without cascading of the input/output operator:-

#include<iostream>
using namespace std;
 
int main () {
   int a, b;
   cin>>a;
   cin>>b;
 
   cout<<"The value of a is";
   cout<<a;
 
   cout<<"The value of b is";
   cout<<b;
 
   return 0;
}

In this example, all cin and cout statements use separate input and output operators respectively However, these statements can be combined by cascading the input and output operators accordingly as shown in this example.

A program with cascading of the input/output operator:-

#include<iostream>
using namespace std;
 
int main () {
  int a, b;
  cin>>a>>b;
 
  cout<<"The value of a is : "<<a;
  cout<<"The value of a is "<<b;
 
  return 0;
}

In this example, the cascaded input operators cin >> a >> b wait for the user to input two values, while the cascaded output operators first display a message followed by the values of a and b respectively. Cascading of input/output operators simplifies code structure and improves readability.

How's article quality?

Last updated on -

Page Contents