In this shot, we will learn how to accept an integer input from a user and print the given input.
The program waits for the user to enter an integer value.
The value entered by the user is then taken using cin
, which is a standard input stream in C++. The cin
method in C++ is used together with the extraction operator, which is written as >>
followed by the variable name where the input value is stored.
int age;
cin >> age;
In the code above, the first statement declares the variable age
of type int
. The second statement stores the input value taken from cin
to the variable age
.
The cout
output stream is then used to print out the value the user entered.
cout << "The value you entered is: " << age << endl;
From the statement above, the cout
method prints the value of the integer passed to the age
variable by the user.
This is the last step in the program because the user input is now read and printed.
The following program reads an integer input and prints its value.
#include <iostream>using namespace std;int main() {// declaring the variable ageint age;// taking input from usercout << "How old are you?: ";cin >> age;// printing the integer inputcout << age << endl << "5 years from now, you will be " << age + 5 << " years old." << endl;return 0;}
Enter the input below