Input in C++ refers to the process of accepting data from the user or an external source so that a program can perform operations on that data. User input makes programs interactive and allows them to work with dynamic values instead of fixed data.
- Enables interaction between the user and the program.
- Allows data to be stored in variables at runtime.
- Can be used to read single values, multiple values, or entire lines of text.
Common Input Methods in C++
C++ provides several ways to accept input from the user. The most commonly used methods are:
Using cin (Standard Input Stream)
The cin object is part of the <iostream> library and is used to read formatted input from the standard input device (usually the keyboard). It uses the extraction operator (>>) to read values and store them in variables.
#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.
Taking Multiple Inputs Using cin
The cin object can read multiple values in a single statement by chaining the extraction operator (>>).
#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.
Using getline() for Multi-word Input
The getline() function is used to read an entire line of text, including spaces.
#include <iostream>
using namespace std;
int main() {
string name;
getline(cin, name);
cout << name;
return 0;
}
Input
John SmithOutput
John SmithExplanation:
- getline(cin, name) reads the complete line entered by the user.
- Unlike cin, it does not stop at spaces.
- Useful for reading names, addresses, and sentences.
Using cin.get() to Read a Character
The cin.get() function is used to read a single character from the input stream.
#include <iostream>
using namespace std;
int main() {
char ch;
cin.get(ch);
cout << ch;
return 0;
}
Input
AOutput
AExplanation:
- cin.get(ch) reads a single character from the input.
- It can also read whitespace characters such as spaces and newlines.
- Useful when character-level input is required.