Input/output
You remember using cout
to display a message. You can use cin
to do
the opposite: get input from the user. It works like this (notice the
>>
of cin
, which are opposite those of cout
):
You can use cin
for integer types, floating point types, string types,
and others. It’s easiest if you ask the user to enter one value at a
time, pressing Enter between each value.
To acquire multiple values at once, just string them together with
cin
:
This is equivalent to:
More examples:
cin
only collects input up to the first space or newline. It can be
used to obtain multiple inputs. It knows when to delimit (i.e. start
looking for the next input) when it reaches a space or newline (or
tab).
Here’s the same example as above, but using just one cin
:
We can get strings in the usual way:
However, using that technique, you cannot get strings that have spaces. To get strings that have spaces in them, we have to use this method:
That method gets a whole line of text, which could have spaces.
Printing with precision
When printing “floating-point values” (such as floats, doubles, etc.) we often need to show a specific number of digits after the decimal point. This is known as the “precision” of the number. The actual precision of the value will not change; we will only change the printed precision. The following will show three digits after the decimal point:
Here is a complete example:
For example,
Enter value for x: 4.444444 You entered 4.444
Enter value for x: 0.0000001 You entered 0.000
Enter value for x: 123.45678 You entered 123.457
Notice how the last printout rounded up; the value of “x” inside the program has not changed, however.