< previous page page_135 next page >

Page 135
When you enter input data at the keyboard, you must be sure that each data value is appropriate for the data type of the variable in the input statement.
Data Type of Variable In an >> OperationValid Input Data
charA single printable character other than a blank
intAn int literal constant, optionally preceded by a sign
floatAn int or float literal constant (possibly in scientific, E, notion), optionally preceded by a sign

Notice that when you input a number into a float variable, the input value doesn't have to have a decimal point. The integer value is automatically coerced to a float value. Any other mismatches, such as trying to input a float value into an int variable or a char value into a float variable, can lead to unexpected and sometimes serious results. Later in this chapter we discuss what might happen.
When looking for the next input value in the stream, the >> operator skips any leading whitespace characters. Whitespace characters are blanks and certain nonprintable characters like the character that marks the end of a line. (We talk about this end-of-line character in the next section.) After skipping any whitespace characters, the >> operator proceeds to extract the desired data value from the input stream. If this data value is a char value, input stops as soon as a single character is input. If the data value is int or float, input of the number stops at the first character that is inappropriate for the data type, such as a whitespace character. Here are some examples, where i, j, and k are int variables, ch is a char variable, and x is a float variable:
StatementDataContents After Input
1. cin >> i ;32i = 32
2. cin >> i >> j ;4 60i = 4, j = 60
3. cin >> i >> ch >> x;25 A 16.9i = 25, ch = A, x = 16.9
4. cin >> i >> ch >> x;25
A
16.9:i = 25, ch = A, x = 16.9
5. cin >> i >> ch >> x;25A16.9i = 25, ch = A, x = 16.9
6. cin >> i >> j >> x;12 8
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
i = 12, j = 8 (Computer waits for a third number)
7. cin >> i >> x;46 32.4 15
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
i = 46, x = 32.4 (15 is held for later input)

 
< previous page page_135 next page >