Standard Input Stream (cin) in C++


std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.

As an object of class istream, characters can be retrieved either as formatted data using the extraction operator (operator>>) or as unformatted data, using member functions such as read. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.

You can use this object to read from standard input to a variable. For example, if you want to read an int value in a variable my_intand then print it to the screen, you'd write −

Example

#include<iostream>
int main() {
   int my_int;
   std::cin >> my_int;
   std::cout << my_int;
   return 0;
}

Then save this program to the hello.cpp file. Finally, navigate to the saved location of this file in the terminal/cmd and compile it using −

$ g++ hello.cpp

Run it using −

$ ./a.out

Output

If you give it the input: 15, this will give the output−

15

Updated on: 10-Feb-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements