Table of Contents
The stream extraction operator (>>) is used to read data from an input stream. It extracts characters from the stream, converts them to the required data type, and stores the result in a variable.
The extraction operator is most commonly used with std::cin to read input from the keyboard. Multiple values can be extracted in a single statement by chaining the operator.
Source Code #
#include <iostream>
int main()
{
int age;
float salary;
std::cout << "Enter age and salary: ";
std::cin >> age >> salary;
std::cout << "Age: " << age << '\n';
std::cout << "Salary: " << salary << '\n';
return 0;
}
Output #
Enter age and salary: 25 45000.5
Age: 25
Salary: 45000.5
Explanation #
- The stream extraction operator (
>>) extracts data from an input stream. std::cinis the standard input stream object used to read data from the keyboard.- The extraction operator reads characters from the input stream, converts them to the destination data type, and stores the result in the specified variable.
- Multiple extraction operators can be chained together to read several values from a single input statement.
- By default, the extraction operator skips leading whitespace such as spaces, tabs, and newline characters before reading the next value.
- Input values must be compatible with the destination variable’s data type. Otherwise, the input operation fails and the stream enters the fail state.
- After successful extraction, the stored values can be displayed using
std::cout. return 0;terminates the program successfully.