Saturday 22 June 2013

Standard Input (cin)

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the
overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will
store the data that is going to be extracted from the stream. For example:

 

The first statement declares a variable of type int called age, and the second one waits for an input from cin(the
keyboard) in order to store it in this integer variable.
cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you
request a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced.
You must always consider the type of the variable that you are using as a container with cin extractions. If you
request an integer you will get an integer, if you request a character you will get a character and if you request a
string of characters you will get a string of characters.


The user of a program may be one of the factors that generate errors even in the simplest programs that use cin
(like the one we have just seen). Since if you request an integer value and the user introduces a name(which
generally is a string of characters), the result may cause your program to mis operate since it is not what we were
expecting from the user. So when you use the data input provided by cin extractions you will have to trust that
the user of your program will be cooperative and that he/she will not introduce his/her name or something similar
when an integer value is requested. A little ahead,when we see the string stream class we will see a possible
solution for the errors that can be caused by this type of user input.
You can also use cin to request more than one datum input from the user:


is equivalent to:


In both cases the user must give two data, one for variable a and another one for variable b that may be separated
by any valid blank separator: a space, a tab character or a newline.