C++ cin
Table of content
Cin : Extracting Input from User Using Keyboard
In C++ Extraction operator is used to accept value from the user.User can able to accept value from user and that value gets stored inside value container i.e. Variable.
Syntax : Get Value from User
cin >> variable;
Explanation : Extraction Operator
- Include <iostream.h> header file to use cin.
#include<iostream.h>//traditional C++ OR #include<iostream>// ANSI Standard using namespace std;
- cin is used for accepting data from the keyboard.
- The operator >> called as extraction operator or get from operator.
- The extraction operator can be overloaded.
- Extraction operator is similar to the scanf() operation in C.
- cin is the object of istream class.
- Data flow direction is from input device to variable.
- Due to the use of input statement, the program will wait till the user type some input and that input is stored in variable.
- Multiple inputs can be accepted using cin.
Live Example : Accepting Input From User
#include<iostream.h> using namespace std; int main() { int number1; int number2; cout<<"Enter First Number: "; cin>>number1; //accept first number cout<<"Enter Second Number: "; cin>>number2; //accept first number cout<<"Addition : "; cout<<number1+number2; //Display Addition return 0; }
Output :
Enter First Number: 8 Enter Second Number: 8 Addition : 16
Different ways of using cin in c++
Way 1. Simple Use of cin and Extraction Operator:
int tempNumber; cin >> tempNumber;
- In above example, tempNumber is declared as integer variable.
- when control comes over cin , Program waits for the input from user.
- We have written integer variable after extraction operator so it will wait and expect integer as input from user .
- If you request an integer you will get an integer, character for character, string for string etc
Way 2 : Cascading Multiple Variables in Cin
int a,b; cin >> a >> b;
is similar to -
int a,b; cin >> a; cin >> b;
While Accepting Two values cin consider next value when it found -
- Space
- Tab
- Newline.
*Note : In this case, User is forced to input two variables (a and b).
Way 3 : cin to get string
cin >> string ; //for getting string input
- The extraction operator is also used for getting string.
- When blank space is detected, extraction operator stops reading input.
- cin allow us to enter only one word.
- For reading entire line, we use getline() function.