Standard Input/Output Stream in C++

Written by

Vaaruni Agarwal

So, far we have learned and used the cin and cout to take inputs from the user and to display a message on the output screen. But have you ever wondered that how they actually work? This is what we will be looking for in this chapter.

The Standard Output Stream (cout):

The predefined object cout is an instance of the ostream class. It is the same cout that is used to display messages, values of variables, escape sequences, etc. on the output screen. 

The cout object is said to be “connected to” the standard output device, which usually is the display screen. It is used in combination with the insertion operator, <<. cout is used to display everything written within the double quotes as it is on the screen.

Example:

#include <iostream>

int main() {

   char str[] = "Hello C++";

    cout << "Value of str is : " << str << endl;

}

When the above code is compiled and executed, it produces the following result −

Value of str is : Hello C++

The multiple insertion operators can be used in a single line as evident from the above example as well.

The Standard Input Stream (cin):

The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. That is it is used to take input from the user, which is done mainly through the keyboard. It is used in conjunction with the stream extraction operator, which is written as >>. There can be multiple >> in a single C++ code line.

Example:

#include <iostream>

int main()

 {

   char fname[50],lname[50];

   cout << "Please enter your first and last name: ";

   cin >> fname>>lname;

   cout << "Your name is: " << fname <<” “<<lname<< endl;

}

 

Standard Input/Output Stream in C++