Table of Contents
Programs often require values to be provided while they are running. In C++, the standard input stream is represented by std::cin, which reads data entered through the keyboard.
This example demonstrates how to read an integer from the user and display the entered value using the standard output stream.
Source Code #
#include <iostream>
int main()
{
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << '\n';
return 0;
}
Output #
Enter a number: 25
You entered: 25
Explanation #
int number;declares an integer variable that stores the value entered by the user.std::cout << "Enter a number: ";displays a prompt before waiting for 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 innumber. std::cout << "You entered: " << number << '\n';displays the value stored in the variable.return 0;terminates the program and returns a success status to the operating system.