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..
[cpp]int x ;
cin >> x ; [/cpp]
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 ..
void main ()
int x ;
cout << " Enter a number : " ;
cin >> x ;
cout << " You entered : " << x ;
Output 1 :
[cpp]Enter a number : 5
You entered : 5 [/cpp]
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 :
[cpp]Enter a number : 25
You entered : 25 [/cpp]
You can even perform different operations on the accepted input. We will see that in next Tutorial.