- The statement
cin >> age;
should be thought of as "get a value for age from the input stream cin",
where cin is associated with the keyboard device. The operator
>> is called the extraction operator.
- The operand to the right of >> must be a variable (that is,
it may not
be a constant or an expression), because it indicates the place in memory
where the input value
will be stored.
- When the input device is the keyboard, values aren't actually read into
the variables until the user types the ENTER key. This gives the user a
chance to use the backspace key if a mistake is made when typing in the
input.
- cin statements skip any whitespace in the input stream. Whitespace
are those characters that cause the cursor to move, but don't display
anything on the monitor: spaces, tabs, and newlines.
- When a program reaches a cin statement, it expects input to be
entered from the keyboard. If none is typed in, the computer simply waits
for it. The computer will not automatically ask the user to enter data.
In an interactive program, every cin statement should be preceded by a
prompt. A prompt is a message to the user of the program telling the
user
that the program expects data to be entered. The cout statement in the
following code fragment is a prompt:
int age;
cout << "Enter your age: ";
cin >> age;
- Multiple inputs can be entered with one cin statement. For example,
the statements
int a, b, c;
cin >> a >> b >> c;
can be used to input values for the three integers a, b, and c. The program
will not continue until it either has values for each of the variables,
or the until the input stream "goes bad".
- The user must make sure that the type of data entered matches the
type of variable that is waiting for the data. If not, the input stream
"goes bad". Given the same code fragment as before...
int age;
cout << "Enter your age: ";
cin >> age;
...suppose the user types in non-numeric data when the program is executed:
Enter your age: Hello!
Since "Hello!" is not an int, cin goes bad, and any further attempts to
read values from cin result in nothing being read. (We'll see how to test
for this condition when we study boolean expressions.)
- The extraction operator >> reads input until the end of the input value is
reached. This occurs by reaching a delimiter, that is, a character that is
not part of a legal input value. The delimiter itself stays in the input
stream, to be read by the next input operation. For example, suppose a program
contains the statements:
int i;
char c;
cin >> i >> c;
Suppose the data typed in by the user is
42xyz
The number 42 will be read into the int variable i, and the
character 'x' will be read into the char variable c. The characters
'y' and 'z' remain in the input stream, perhaps to be read at a later time.