I/O Manipulation:
Among others, the manipulator dec is found in the
iomanip library. It is used to force cin to interpret
numbers in base 10. cin's default behavior is to
guess the number base by the first character/digit
of the number:
01462 octal (base 8) (equals 2+6*8+4*64+1*512=818 base 10)
xAF hexadecimal (base 16) (equals 15+10*16=175 base 10)
462 decimal (base 10)
So a leading zero (0) is seen as an octal value. A leading
letter x is seen to indicate heXadecimal. Anything else is
seen as a decimal value.
Of course all of this only applies to integer inputs...
Garbage Characters:
Human notation is full of garbage characters which simply
denote position to the human brain. The computer (and
probably your program, too) could care less. But to allow
our human users a more natural interface, we can simply
ignore those garbage characters on input. For instance:
9:00 would be 9 in the morning
9°6'42" would be 9 degrees, 6 minutes, 42 seconds
(4.2,-9) would be an XY coordinate of 4.2 x and -9 y
(847)555-1234 would be a phone number in area code 847,
exchange 555, and line number 1234
4/8/01 would be April 8th, 2001
To remove such positional characters, you can simply use a
character variable in your input stream:
cin >> hour >> temp >> minute;
Would read an hour, a temporary character, and a minute.
cin >> temp >> area >> temp >> exchange >> temp >> line;
Would read in a temporary character (for '('), an area code,
a temporary character (for ')' -- overwriting the '('), an
exchange, a temporary character (for '-' -- overwriting the
')'), and a line number.
Pretty Output:
Although it would look nicer to be able to display 9:09
for the user, cout doesn't like to place leading 0's on
numbers. After all, how would it know how many or that
that first 9 didn't need a leading 0?
To fix this, there are formatting options in chapter 5
(which we'll learn in 122) or branching instructions
(which we'll get to in chapter 2.4 and 7).