370 likes | 532 Views
C++ Stream Input/Output. Chapter 11. 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. Introduction. Many I/O features are object oriented
E N D
C++ Stream Input/Output Chapter 11
What You Will Learn • Using C++ object oriented stream input and output • Formatting I/O, creating manipulators • I/O Class hierarchies • Determine streamsuccess or failure
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
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
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
Multiple inheritance Base Class Input Output File I/O File Class Hierarchy ios istream ostream iostream iostream.h fstream.h ifstream fstream ofstream
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
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 <<
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;
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);
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
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
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)
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
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
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
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
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
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);
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
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";
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
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
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;
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
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)
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)
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? (Fig. 11-24) xxx5
Integral Stream Base • Use showbase flag cout << setiosflags (ios::showbase) << x << endl << oct << x << endl << hex << x << endl;
Floating-Point Numbers • We have used in previous course cout.setf (ios::fixed, ios::floatfield); • Also possible to specify scientific notationcout.setf (ios::scientific, ios::floatfield); • Can be turned off with cout.unsetf (ios::scientific);
Uppercase/Lowercase Control • Forces uppercase letters for • scientific notation • hex notation • Usecout << setiosflags (ios::uppercase) << 1.23e6;
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);
Stream 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( )
Stream 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
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);