Simple user input in integer form
Learning the ways to take simple user input in integer form.
Learning Objectives
- Collecting simple user input in an integer form.
- use of cin and io extraction operator.
Program Approach
- Create an space where the user input would be stored.
- Prompt the user for an input using the cout.
- Collect the user input using cin and >> (io extraction operator)
- Display the input given by the user.
Source Code
|
Run Output
Code Understanding
int n;
Here we declare a variable of our choice. In this case we have named it n. For this we decide to use the integer data type.
cout<<“Enter an integer number: “;
This line is used to prompt the user what has to be input.
cin>>n;
This is the line which collects the user input using the cin object in c++.. This object is followed by >> operator which is also called the “io extraction operator”. Some literature also name it as the “get from console” operator.
cout<<“You have entered “<<n<<endl;
This line is used to display the output as entered by the user. n is the variable which will be filled by the user when cin collects the required data.
Notes
In this code if user input is not an integer,say it is a fraction value like 23.45, then cin will still collect it. But! since the storage variable n is of integer type, thus the stored value will only be the integer portion of the input. So the output will only be 23.
Suggested Filename(s): simpleinput.cpp, intinput.cpp
CSKC| Created: 14-Dec-2017 | Updated: 31-Aug-2018|