How to take an integer input in C++

Overview

In this shot, we will learn how to accept an integer input from a user and print the given input.

Step 1

The program waits for the user to enter an integer value.

Step 2

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.

Step 3 (syntax)

int age;
cin >> age;

Step 4

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.

Step 5

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.

Example

The following program reads an integer input and prints its value.

#include <iostream>
using namespace std;
int main() {
// declaring the variable age
int age;
// taking input from user
cout << "How old are you?: ";
cin >> age;
// printing the integer input
cout << age << endl << "5 years from now, you will be " << age + 5 << " years old." << endl;
return 0;
}

Enter the input below

Free Resources