cout and cin in C++

This tutorial will teach you about the popularly used standard input and output streams cout and cin in C++. cout keyword is used to print the output on the screen and cin keyword is used to read the input from the user. We must include header file iostream in our program to use cin and cout.

cout and cin in C++

In C++, we have streams that perform input and output in the form of sequences of bytes. A program inserts some data into the stream while giving output and extracts data from the stream while taking input. cout and cin are the standard input/output streams.

If you are interested in: Taking only integer input in C++

Standard Output Stream in C++

cout is the standard output stream. It is an instance of ostream class. It usually prints the output on the standard output device, usually your screen. We use the insertion operator (<<) to insert the output data into the output stream.

Example program for cout:

#include<iostream>
using namespace std;

int main()
{
  cout<<"prints the output.";
  cout<<10;
  return 0;
}

Output:

prints the output.10

As you can see in the example, we have printed “prints the output.” and 10 using cout and insertion operator (<<). Double quotes are used to insert a string literal into the output stream.

We can also print values stored by different variables using cout. In such cases, we don’t use the double-quotes. See the example below.

#include<iostream>
using namespace std;

int main()
{
  int a=10;
  cout<<a;
  return 0;
}

The output of the above example is:

10

We can also use multiple insertion operator(<<) to give a single output. The below program explains this property.

#include<iostream>
using namespace std;

int main()
{
  cout<<"prints the output."<<10;
  return 0;
}

Output:

prints the output.10

Standard Input Stream in C++

cin is the standard input stream in C++. It is an instance of istream class. It reads input from a standard input device which is, most often, the keyboard. We use the extraction operator (>>) along with cin to get the input from user. This operator extracts the data from the input stream.

See the implementation here.

#include<iostream>
using namespace std;

int main()
{
  int a;
  cout<<"Enter an integer value.\n";
  cin>>a;
  cout<<"You entered "<<a;
  return 0;
}

The output of the above program is:

Enter an integer value.
6
You entered 6

We can use multiple extraction operator (>>) in our program to read different inputs in a single statement, just like we did in cout. See this program.

#include<iostream>
using namespace std;

int main()
{
  int a,b;
  cout<<"Enter two integer values.\n";
  cin>>a>>b;
  cout<<"You entered "<<a<< " and " <<b;
  return 0;
}

Output:

Enter two integer values.
43 5
You entered 43 and 5

Also read:

Leave a Reply