Lecture Notes for Introduction to Computer Science II
24 July 2001 - Formatted I-O
- formatted vs. unformatted i-o
- unformatted i-o doesn't change the data being read or written
- formatted i-o changes the data being read or written
- why change - 3 is not the same as '3' or "3"
- humans understand with characters; machines understand with bits
- characters go to and come from humans
- but characters are bits - but bits of the wrong kind
- 3 = 0000000000000011 and '3' = 0000001100000011 = 51
- for humans to understand 3, it has to be output as '3' (or 51)
- how change - convert numbers to characters and vice versa
- the number 100 has to be changed into the characters '1', '0', and
'0'
- the characters '5', '2', and '1' have to be converted into the number
512
- formatted i-o converts between numbers and characters in both
directions
- not only numbers can be converted
- characters - not much of a conversion
- strings - ditto
- booleans
- even objects
- stream extraction (input) and insertion (output)
- the stream insertion operator
outs << value
-
outs
is an io stream opened for writing
-
value
is a value of a type the insertion operator knows how to
convert (int
, char
, string
and so on)
-
value
is converted into characters
- the characters are appended to the stream at the file pointer
- the file pointer moves to the byte just after the last byte written
- the stream extraction operator
ins >> var
- extraction is not as simple as insertion
-
ins
is an io stream opened for reading
-
var
is a variable having a type the extraction operator knows
how to convert
- starting at the file pointer, extraction reads as many bytes as
there are consistent with the type of value being read
- for integers - the characters
'0'
through
'9'
possibly proceeded by either '-'
or
'+'
; all the digits are read, but not necessarily used
- for characters - the next bytes, single quotes not needed
- the file pointer points to the next byte after the last byte read
- the characters are converted to the proper value and assigned to
var
- whitespace and stream extraction
- in general, stream extraction does not consider white-space
characters as being part of any value, including strings
- white-space characters include space, tab, and newline
- initial whitespace is skipped
- trailing whitespace ends extraction
- incorrect input
- if the input characters don't match the expected value, the
extraction fails
- the file pointer does not advance past the bad character - white
space stays skipped over
-
var
does not receive a value
-
good()
returns false
- extraction and insertion return the stream involved
- cascading insertions and extractions -
cout << "i = "
<< i << "\n"
- if
cin
hits eof, it returns NULL
- while (cin >> i)
This page last modified on 23 July 2001.