Input in C++ refers to the process of reading data from the user or an external source and storing it in program variables. C++ provides multiple input mechanisms to handle different data types and input formats efficiently. The most commonly used input method is the cin object, which reads data from the standard input device (keyboard).
1. Using cin (Standard Input Stream)
The cin object is part of the <iostream> library and is widely used for taking input in C++ programs. It uses the extraction operator (>>) to read data and store it in variables.
Example 1: Taking a Single Input Using cin
#include <iostream>
using namespace std;
int main(){
int i;
// Take input using cin
cin >> i;
// Print output
cout << i;
return 0;
}
Input:
10
Output:
10
Explanation:
- The cin >> i; statement reads an integer value from the user.
- The value entered is stored in variable i.
- The output is displayed using cout.
2. Taking Multiple Inputs Using cin
The cin object allows reading multiple input values in a single statement by separating them with the extraction operator (>>
Example 2: C++ program to take multiple input from the user using the cin object:
#include <iostream>
using namespace std;
int main(){
string name;
int age;
// Take multiple input using cin
cin >> name >> age;
// Print output
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
return 0;
}
Input:
ABC
10
Output:
Name : ABC
Age : 10
Explanation:
- The cin >> name >> age; statement reads a string followed by an integer.
- Each value is stored in the corresponding variable in the order entered.
- cin stops reading a string at whitespace, making it suitable for single-word inputs.