Getting Input from the User in C++

Now lets learn how to get input from the user, how to store that input, and how to display that input as output. To show the output we used a keyword called cout (console out). Similarly to get the input there is a keyword called cin (console in). But there is one more difference. While using cout we used an insertion operator (<<). This insertion operator was having two less than signs. But while using cin we will use the insertion operator (>>). This insertion operator has two greater than signs.

Now lets understand practically..

In the above code, we ‘declared‘ a variable x of the integer datatype. Then on the second line, we have cin >> x. That means we are getting the input from the console and storing it inside the variable x. So value is being taken from the user and being stored inside variable x using the insertion operator having two greater than signs.

Lets understand this with the help of a simple program ..

Code :

Output 1 :

In the code above, we have put our basic code as learned in the previous tutorials. Then inside the main function we have declared variable x of the integer datatype. Then we displayed “Enter a number : ” on the screen, asking the user to enter a number. User can enter any value. In this case, I entered the value 5. Then after next statement is executed which displays “You entered : ” string on the screen ALONG with the VALUE stored within variable x.

So if  i run the program again and enter some other value then this will be the output :

Output 2 :

You can even perform different operations on the accepted input. We will see that in next Tutorial.

Leave a Reply