Post on 05-Jan-2016
description
1
C++ Stream Input/Output
Chapter 11
2
What You Will Learn
Using C++ object oriented stream input and output
Formatting I/O, creating manipulators
I/O Class hierarchies Determine stream
success or failure
3
Introduction
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
4
Streams
Defn => 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
5
IOstream Library Header files
We use the #include <iostream.h> Contains basic infor required for all
stream-I/O operations cin, cout, cerr, clog
#include <iomanip.h> formatted I/O with parameterized
stream manipulators #include <fstream.h>
file processing operations
6
File Class Hierarchy
ios
istream ostream
iostream
ifstream fstream ofstream
iostream.h
fstream.h
InputOutput
File I/O
Multiple inheritanceBase Class
7
Stream I/O Classes & Objects
>> and << 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
8
Stream-Insertion Operator
<< operator overloaded to output data items of built in types strings pointer values
When outputting expressions, use parentheses avoids confusion of operator
precedence with <<
9
Cascading Insertion/Extraction Operators
<< associates from left to right Overloaded << 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 << "total = " << a + b;cout << "total = " << a + b;
10
Output of char * Variables
Consider data object of type char* a character stringcout << 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 << static_cast<void *>(name);
11
Char 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
12
Stream Input
Performed with extraction operator >> 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
13
Stream-Extraction Operator
Stream extraction can be cascaded Warnings
don't try extraction >> with cout don't try insertion << with cin possible need of parentheses due to
precedence of << and >> while (cin) …
specify end of I/O with ctrl-z (ctrl-d on Mac or UNIX)
14
get 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
15
get 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
16
get 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
17
istream 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
18
Type-Safe I/O
<< and >> 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
19
Unformatted 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);
20
Stream 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
21
Integral Stream Base
Integers normally interpred as base 10 (decimal) values
Make sure to #include <iomanip.h> Specify other bases with
hex for base 16 (hexadecimal) oct for base 8 (octal)
cout << n << " = " << oct << n << " in octal";
22
Floating-Point Precision
Specify number of decimal digits shown (rounded to that # digits)
Make sure to #include <iomanip.h> And to cout.setf (ios::fixed); // orcout << setiosflags (ios::fixed);
Use cout << setprecision (places) ;or cout.precision (places);
Author notes -- setting precision to 0 may result in default precision setting
23
Field Width
Two versionscout.width(places); // andcout << setw (places);
If values take up less space, padding added to left => right justify
If values take up more space, width specification is overridden thus may push succeeding
columns of output to the right
24
User-Defined Manipulators// bell manipulator (using escape sequence \a)ostream& bell( ostream& output ) { return output << '\a'; } // ret manipulator (using escape sequence \r)ostream& ret( ostream& output ) { return output << '\r'; } // tab manipulator (using escape sequence \t )ostream& tab( ostream& output ) { return output << '\t'; }
Note use of
- return type is ostream&
- parameter type is ostream&
Usage : cout << 'a' << tab << 'c' << bell;
25
Format State Flags
Note table on pg 621 (Fig. 11.20) These flags controlled by
flags ( … ) cout.setf ( … ) member cout.unsetf ( … ) functions setiosflags ( … )
// in the << sequence
26
Trailing Zeros, Decimals
Use ios::showpoint floating point values print as
integers if that is what is stored showpoint forces decimal points to
be printed for floats
(Fig 11.21)
27
Justification Use ios::left ios::right
ios::internal Right justification is default with
setw( ) padded characters added on
right when ios::left is specified ios::internal => a number's sign
left justified, magnitude right justified
(Fig. 11.21)
28
Padding
The cout.fill('x'); specifies that padding be x's instead of spaces
Alternative version cout << setfill('x') << setw(4) << 5;
What would output would be?xxx5 (Fig. 11-24)
29
Integral Stream Base
Use showbase flag
cout << setiosflags (ios::showbase) << x << endl << oct << x << endl << hex << x << endl;
cout << setiosflags (ios::showbase) << x << endl << oct << x << endl << hex << x << endl;
30
Floating-Point Numbers
We have used in previous course cout.setf (ios::fixed, ios::floatfield);
Also possible to specify scientific notation cout.setf (ios::scientific, ios::floatfield);
Can be turned off with cout.unsetf (ios::scientific);
31
Forms of setf( )
32
Uppercase/Lowercase Control
Forces uppercase letters for scientific notation hex notation
Usecout << setiosflags (ios::uppercase) << 1.23e6;
33
Setting/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);
34
Stream Error States
Base class ios has bits which tell state of I/O eofbit set when end-of-file
use cin.eof( ) failbit set when format error
with no loss of charuse cin.fail( )
35
Stream Error States
badbit set for error with lost datause cin.bad( )
goodbit set if none of eofbit, failbitor badbit are set
use cin.good( ) cin.rdstate( ) returns errorstate of
stream cin.clear( ) restores stream state
to good
36
Tying 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);