Title: C Stream Input/Output
1C Stream Input/Output
2What You Will Learn
- Using C object oriented stream input and output
- Formatting I/O, creating manipulators
- I/O Class hierarchies
- Determine streamsuccess or failure
3Introduction
- Many I/O features are object oriented
- Uses function and operation overloading
- We will see type safe I/O
- operations performed sensitive to the data type
- if no I/O function exists for a given type, then
compiler notes as error
4Streams
- Defn gt a sequence of bytes
- I/O moves them from/to secondary devices
- Applications associate meaning to the bytes
- I/O is extremely slow compared to processing
speeds - C provides both formatted and unformatted I/O
5IOstream Library Header files
- We use the include ltiostream.hgt
- Contains basic infor required for all stream-I/O
operations - cin, cout, cerr, clog
- include ltiomanip.hgt
- formatted I/O with parameterized stream
manipulators - include ltfstream.hgt
- file processing operations
6File Class Hierarchy
ios
istream
ostream
iostream
iostream.h
fstream.h
ifstream
fstream
ofstream
7Stream I/O Classes Objects
- gtgt and ltlt are right and left bit shift operators
- Have been overloaded for input and output
- cin is an object of class istream
- tied to standard input, keyboard
- cout is an object of class ostream
- tied to standard output, screen
8Stream-Insertion Operator
- ltlt operator overloaded to output data items of
- built in types
- strings
- pointer values
- When outputting expressions, use parentheses
- avoids confusion of operator precedence with ltlt
9Cascading Insertion/Extraction Operators
- ltlt associates from left to right
- Overloaded ltlt operator returns a reference to its
left-operand object (cout) - Next cascaded operand sent to the result of the
first function call (which points to cout)
cout ltlt "total " ltlt a b
10Output of char Variables
- Consider data object of type char
- a character stringcout ltlt name//contents of
array printed - What if we wish to print the value of the pointer
the address to which it points? - Cast the pointer to void cout ltlt
static_castltvoid gt(name)
11Char Output with put
- put is a member function of ostream
- Sends a single character value to the output
stream - The function returns reference to object which
called it (cout) - thus can be cascadedcout.put('W').put('O').put('W
') - Integer value parameter taken in as ASCII
character number
12Stream Input
- Performed with extraction operator gtgt
- Normally skips whitespace characters
- blanks, tabs, newlines
- Operator returns zero (false) when eof occurs
- otherwise returns reference to stream object
(thus can be cascaded) - Stream has state bits used to control state of
stream
13Stream-Extraction Operator
- Stream extraction can be cascaded
- Warnings
- don't try extraction gtgt with cout
- don't try insertion ltlt with cin
- possible need of parentheses due to precedence of
ltlt and gtgt - while (cin) specify end of I/O with ctrl-z
(ctrl-d on Mac or UNIX)
14get and getline Member Functions
- ch cin.get( )// inputs returns one
character - even if it is whitespace -- returns the
whitespace character - returns the EOF when end of file reached
- cin.eof( )returns true (1) when user enters ctrl-z
15get and getline Member Functions
- cin.get(ch) // new version
- reads value from stream into ch
- returns 0 when eof encountered
- otherwise returns reference to stream object (for
cascading) - cin.get (name, 30,'\n') // 3rd version
- 30 specifies max number of characters
- '\n' terminates input
- '\n' not consumed
16get and getline Member Functions
- cin.getline(name,30,'\n')
- Similar to cin.get( )
- Difference is that the getline version will
"consume" the '\n' (or whatever delimiter is
specified) - Need to be aware of using cin.ignore if we know
'\n' will still be in the stream
17istream Member Functions
- ignore -- skips over designated number of
characters - putback -- places character previously obtained
with get back onto input stream - good for scanning a stream looking for specific
character - peek -- returns next character in stream without
getting it off the stream
18Type-Safe I/O
- ltlt and gtgt overloaded to accept data items of
specific types - that is, there are separate overloaded operators
for different types of operands (function
parameters) - Error flags set if wrong type of data comes
through the stream
19Unformatted I/O
- Performed with read and write member functions
- They take two parameters
- an array of char or a buffer
- a number which tells how many characterscin.read(
buffer,20)cin.write (buffer,15)
20Stream Manipulators
- Provided for formatting I/O
- Capabilities included
- setting field widths
- setting decimal precision
- set/unset format flags
- setting fill in char fields
- flushing streams
21Integral Stream Base
- Integers normally interpred as base 10 (decimal)
values - Make sure to include ltiomanip.hgt
- Specify other bases with
- hex for base 16 (hexadecimal)
- oct for base 8 (octal)cout ltlt n ltlt " " ltlt
oct ltlt n ltlt " in octal"
22Floating-Point Precision
- Specify number of decimal digits shown (rounded
to that digits) - Make sure to include ltiomanip.hgt
- And to cout.setf (iosfixed) // orcout ltlt
setiosflags (iosfixed) - Use cout ltlt setprecision (places) or
cout.precision (places) - Author notes -- setting precision to 0 may result
in default precision setting
23Field Width
- Two versionscout.width(places) // andcout ltlt
setw (places) - If values take up less space, padding added to
left gt right justify - If values take up more space, width specification
is overridden - thus may push succeeding columns of output to the
right
24User-Defined Manipulators
// bell manipulator (using escape sequence
\a) ostream bell( ostream output ) return
output ltlt '\a' // ret manipulator (using
escape sequence \r) ostream ret( ostream output
) return output ltlt '\r' // tab
manipulator (using escape sequence \t ) ostream
tab( ostream output ) return output ltlt '\t'
Note use of - return type is ostream - parameter
type is ostream Usage cout ltlt 'a' ltlt tab ltlt
'c' ltlt bell
25Format State Flags
- Note table on pg 621 (Fig. 11.20)
- These flags controlled by
- flags ( )
- cout.setf ( ) member
- cout.unsetf ( ) functions
- setiosflags ( ) // in the ltlt sequence
26Trailing Zeros, Decimals
- Use iosshowpoint
- floating point values print as integers if that
is what is stored - showpoint forces decimal points to be printed for
floats
(Fig 11.21)
27Justification
- Use iosleft iosright iosinternal
- Right justification is default with setw( )
- padded characters added on right when iosleft
is specified - iosinternal gt a number's sign left justified,
magnitude right justified
(Fig. 11.21)
28Padding
- The cout.fill('x') specifies that padding be
x's instead of spaces - Alternative version cout ltlt setfill('x') ltlt
setw(4) ltlt 5 - What would output would be?
(Fig. 11-24)
xxx5
29Integral Stream Base
cout ltlt setiosflags (iosshowbase) ltlt x ltlt
endl ltlt oct ltlt x ltlt endl ltlt hex ltlt x ltlt
endl
30Floating-Point Numbers
- We have used in previous course cout.setf
(iosfixed, iosfloatfield) - Also possible to specify scientific notation
cout.setf (iosscientific,
iosfloatfield) - Can be turned off with cout.unsetf
(iosscientific)
31Forms of setf( )
32Uppercase/Lowercase Control
- Forces uppercase letters for
- scientific notation
- hex notation
- Usecout ltlt setiosflags (iosuppercase) ltlt
1.23e6
33Setting/Resetting Format Flags
- flags ( ) member function without parameters
returns long value with current settings of
format flags - store in a long variable long setting
cout.flags( ) - then later on use with argumentcout.flags
(setting)
34Stream Error States
- Base class ios has bits which tell state of I/O
- eofbit set when end-of-fileuse cin.eof( )
- failbit set when format error with no loss
of charuse cin.fail( )
35Stream Error States
- badbit set for error with lost datause cin.bad(
) - goodbit set if none of eofbit, failbit or
badbit are setuse cin.good( ) - cin.rdstate( ) returns errorstate of stream
- cin.clear( ) restores stream state to good
36Tying an Output Stream to an Input Stream
- Interactive programs use istream for input,
ostream for output - Prompt must first appear
- Only when output buffer fills or is flushed can
input proceed - To explicitly tie these cout and cin
togethercin.tie (cout)