C++ Taking Input From User

In this C++ program, we will learn about taking input from user using cin stream.

For Input, C++ programming language uses an abstraction called streams which are sequences of bytes. cin is a predefined object of class istream. cin object by default is attached to the standard input device which is keyboard in most programming environments. cin along with extraction operator (>>) is used to take keyboard input from user.
Extraction operator is followed by a variable where the input data is stored. cin is an input statement, hence programs waits for user to enter input from keyboard and press enter. Input data flows directly from keyboard to variable.

For Example :
Taking one integer input from user.
int count;
cin >> count;
Taking multiple integer input from user.
int count, sum;
cin >> count >> sum;

The cin can be used to receive the input data like integer, character, float, double etc. Based on the data type of the variable after extraction operator(>>) cin determine how it interprets the characters read from the input.


C++ Program to Take Input From User Using Cin

// C++ Program to take input from user
#include <iostream>
using namespace std;

int main() {
    char word[40];
    int i_var;
    float f_var;
    // Taking integer input from user 
    cout<<"Enter an integer\n";
    cin >> i_var;
 
    // Taking float input from user
    cout << "Enter a floating point value\n";
    cin >> f_var;
 
    // Taking a word as input from user
    cout << "Enter a word\n";
    cin >> word;
 
    // Printing values 
    cout << i_var << endl << f_var << endl 
         << word;
 
    return 0;
}
Output
Enter an integer
4
Enter a floating point value
4.5
Enter a word
program
4
4.5
program

In above program, we take an integer, a float and a string as input from user and store it in variable i_var, f_var and word respectively using cin. Then we print the values entered by user using cout.