Table of Contents
The standard input stream is used to read data entered by the user. In C++, the object std::cin represents the standard input stream provided by the <iostream> library.
This example demonstrates how to read an integer value from the keyboard and display it on the console.
Source Code #
#include <iostream>
int main()
{
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Age: " << age << '\n';
return 0;
}
Output #
Enter your age: 25
Age: 25
Explanation #
int age;declares an integer variable that stores the value entered by the user.std::cout << "Enter your age: ";displays a prompt before accepting input.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 required data type, and stores the result inage. - The extraction operator skips leading whitespace before reading the input value.
- If the entered value cannot be converted to the target data type, the input operation fails and the stream enters the fail state.
std::cout << "Age: " << age << '\n';prints the value stored in the variable.return 0;terminates the program successfully.