1、Chapter 21 - C+ Stream Input/Output,Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion Operator 21.3.2 Cascading Stream-Insertion/Extraction Operators 21.3.3 Output of char * Variables
2、21.3.4 Character Output with Member Function put; Cascading puts 21.4 Stream Input 21.4.1 Stream-Extraction Operator 21.4.2 get and getline Member Functions 21.4.3 istream Member Functions peek, putback and ignore 21.4.4 Type-Safe I/O 21.5 Unformatted I/O with read, gcount and write,Outline (continu
3、ed) 21.6 Stream Manipulators 21.6.1 Integral Stream Base: dec, oct, hex and setbase 21.6.2 Floating-Point Precision (precision, setprecision) 21.6.3 Field Width (setw, width) 21.6.4 User-Defined Manipulators 21.7 Stream Format States 21.7.1 Format State Flags 21.7.2 Trailing Zeros and Decimal Points
4、 (ios:showpoint) 21.7.3 Justification (ios:left, ios:right, ios:internal) 21.7.4 Padding (fill, setfill) 21.7.5 Integral Stream Base (ios:dec, ios:oct, ios:hex, ios:showbase) 21.7.6 Floating-Point Numbers; Scientific Notation (ios:scientific, ios:fixed) 21.7.7 Uppercase/Lowercase Control (ios:upperc
5、ase) 21.7.8 Setting and Resetting the Format Flags (flags, setiosflags, resetiosflags) 21.8 Stream Error States 21.9 Tying an Output Stream to an Input Stream,Chapter 21 - C+ Stream Input/Output,21.1 Introduction,Many C+ I/O features are object-oriented Use references, function overloading and opera
6、tor overloading C+ uses type safe I/O Each I/O operation is automatically performed in a manner sensitive to the data type Extensibility Users may specify I/O of user-defined types as well as standard types,21.2 Streams,Stream A transfer of information in the form of a sequence of bytesI/O Operation
7、s: Input: A stream that flows from an input device ( i.e.: keyboard, disk drive, network connection) to main memory Output: A stream that flows from main memory to an output device ( i.e.: screen, printer, disk drive, network connection),21.2 Streams (II),I/O operations are a bottleneck The time for
8、 a stream to flow is many times larger than the time it takes the CPU to process the data in the streamLow-level I/O Unformatted Individual byte unit of interest High speed, high volume, but inconvenient for people High-level I/O Formatted Bytes grouped into meaningful units: integers, characters, e
9、tc. Good for all I/O except high-volume file processing,21.2.1 Iostream Library Header Files,iostream library: : Contains cin, cout, cerr, and clog objects : Contains parameterized stream manipulators: Contains information important to user-controlled file processing operations,21.2.2 Stream Input/O
10、utput Classes and Objects,ios: istream and ostream inherit from ios iostream inherits from istream and ostream. (right-shift operator) Overloaded as stream extraction operator Both operators used with cin, cout, cerr, clog, and with user-defined stream objects,21.2.2 Stream Input/Output Classes and
11、Objects (II),istream: input streamscin someVariable; cin knows what type of data is to be assigned to someVariable (based on the type of someVariable). ostream: output streams cout someVariable; cout knows the type of data to output cerr someString; Unbuffered - prints someString immediately. clog s
12、omeString; Buffered - prints someString as soon as output buffer is full or flushed,21.3 Stream Output,ostream: performs formatted and unformatted output Uses put for characters and write for unformatted characters Output of numbers in decimal, octal and hexadecimal Varying precision for floating po
13、ints Formatted text outputs,21.3.1 Stream-Insertion Operator, is overloaded to output built-in types Can also be used to output user-defined types cout n; Prints newline character cout endl; endl is a stream manipulator that issues a newline character and flushes the output buffer cout flush; flush
14、flushes the output buffer,21.3.2 Cascading Stream-Insertion/Extraction Operators, : Associates from left to right, and returns a reference to its left-operand object (i.e. cout). This enables cascading cout “How“ “ are“ “ you?“;Make sure to use parenthesis:cout “1 + 2 = “ (1 + 2); NOT cout “1 + 2 =
15、“ 1 + 2;,21.3.3 Output of char * Variables, will output a variable of type char * as a stringTo output the address of the first character of that string, cast the variable as type void *,1. Initialize string2. Print string2.1 cast into void *2.2 Print value of pointer (address of string)Program Outp
16、ut,Value of string is: test Value of static_cast( string ) is: 0046C070,21.3.4 Character Output with Member Function put; Cascading puts,put member function Outputs one character to specified streamcout.put( A); Returns a reference to the object that called it, so may be cascadedcout.put( A ).put( n
17、 ); May be called with an ASCII-valued expressioncout.put( 65 ); Outputs A,21.4 Stream Input, (stream-extraction) Used to perform stream input Normally ignores whitespaces (spaces, tabs, newlines) Returns zero (false) when EOF is encountered, otherwise returns reference to the object from which it w
18、as invoked (i.e. cin) This enables cascaded input cin x y; controls the state bits of the stream failbit set if wrong type of data input badbit set if the operation fails,21.4.1 Stream-Extraction Operator, and grade) Extraction returns 0 (false) when EOF encountered, and loop ends,1. Initialize vari
19、ables2. Perform loop3. OutputProgram Output,Enter grade (enter end-of-file to end): 67 Enter grade (enter end-of-file to end): 87 Enter grade (enter end-of-file to end): 73 Enter grade (enter end-of-file to end): 95 Enter grade (enter end-of-file to end): 34 Enter grade (enter end-of-file to end): 9
20、9 Enter grade (enter end-of-file to end): Z Highest grade is: 99,21.4.2 get and getline Member Functions,cin.get(): inputs a character from stream (even white spaces) and returns itcin.get( c ): inputs a character from stream and stores it in c,21.4.2 get and getline Member Functions (II),cin.get(ar
21、ray, size): Accepts 3 arguments: array of characters, the size limit, and a delimiter ( default of n). Uses the array as a buffer When the delimiter is encountered, it remains in the input stream Null character is inserted in the array Unless delimiter flushed from stream, it will stay therecin.getl
22、ine(array, size) Operates like cin.get(buffer, size) but it discards the delimiter from the stream and does not store it in array Null character inserted into array,1. Initialize variables2. Input data2.1 Function call3. OutputProgram Output,Before input, cin.eof() is 0 Enter a sentence followed by
23、end-of-file: Testing the get and put member functionsZ Testing the get and put member functions EOF in this system is: -1 After input cin.eof() is 1,1. Initialize variables2. Input2.1 Function call3. OutputProgram Output,Enter a sentence: Using the getline member functionThe sentence entered is: Usi
24、ng the getline member function,21.4.3 istream Member Functions peek, putback and ignore,ignore member function Skips over a designated number of characters (default of one) Terminates upon encountering a designated delimiter (default is EOF, skips to the end of the file) putback member function Plac
25、es the previous character obtained by get back in to the stream. peek Returns the next character from the stream without removing it,21.4.4 Type-Safe I/O, operators Overloaded to accept data of different types When unexpected data encountered, error flags set Program stays in control,21.5 Unformatte
26、d I/O with read, gcount and write,read and write member functions Unformatted I/O Input/output raw bytes to or from a character array in memory Since the data is unformatted, the functions will not terminate at a newline character for example Instead, like getline, they continue to process a designa
27、ted number of characters If fewer than the designated number of characters are read, then the failbit is set gcount: Returns the total number of characters read in the last input operation,1. Initialize objects2. Input3. OutputProgram Output,Enter a sentence: Using the read, write, and gcount member
28、 functions The sentence entered was: Using the read, writ,21.6 Stream Manipulators,Stream manipulator capabilities Setting field widths Setting precisions Setting and unsetting format flags Setting the fill character in fields Flushing streams Inserting a newline in the output stream and flushing th
29、e stream Inserting a null character in the output stream and skipping whitespace in the input stream,21.6.1 Integral Stream Base: dec, oct, hex and setbase,oct, hex, or dec: Change base of which integers are interpreted from the stream. Example: int n = 15;cout Accepts an integer argument (10, 8, or
30、 16)cout setbase(16) n; Parameterized stream manipulator - takes an argument,1. Load header1.1 Initialize variables2. Input number3. Output in hex3.1 Output in octal3.2 Output in decimal,Program Output,Enter a decimal number: 20 20 in hexadecimal is: 14 20 in octal is: 24 20 in decimal is: 20,21.6.2
31、 Floating-Point Precision (precision, setprecision),precision Member function Sets number of digits to the right of decimal pointcout.precision(2); cout.precision() returns current precision setting setprecision Parameterized stream manipulator Like all parameterized stream manipulators, required Sp
32、ecify precision: cout setprecision(2) x; For both methods, changes last until a different value is set,21.6.3 Field Width(setw,width),ios width member function Sets field width (number of character positions a value should be output or number of characters that should be input) Returns previous widt
33、h If values processed are smaller than width, fill characters inserted as padding Values are not truncated - full number printed cin.width(5); setw stream manipulator cin setw(5) string; Remember to reserve one space for the null character,1. Initialize variables2. Input sentence2.1 Set width2.2 Loo
34、p and change width3. Output,Program Output,Enter a sentence: This is a test of the width member function Thisisatestofthewidthmemberfunction,21.6.4 User-Defined Manipulators,We can create our own stream manipulators bell ret (carriage return) tab endLineParameterized stream manipulators Consult inst
35、allation manuals,21.7 Stream Format States,Format flags Specify formatting to be performed during stream I/O operationssetf, unsetf and flags Member functions that control the flag settings,21.7.1 Format State Flags,Format State Flags Defined as an enumeration in class ios Can be controlled by membe
36、r functions flags - specifies a value representing the settings of all the flags Returns long value containing prior options setf - one argument, “ors“ flags with existing flags unsetf - unsets flags setiosflags - parameterized stream manipulator used to set flags resetiosflags - parameterized strea
37、m manipulator, has same functions as unsetf Flags can be combined using bitwise OR ( | ),21.7.2 Trailing Zeros and Decimal Points (ios:showpoint),ios:showpoint Forces a float with an integer value to be printed with its decimal point and trailing zeroscout.setf(ios:showpoint)cout 79;79 will print as
38、 79.00000 Number of zeros determined by precision settings,21.7.3 Justification (ios:left, ios:right, ios:internal),ios:left Fields to left-justified with padding characters to the rightios:right Default setting Fields right-justified with padding characters to the leftCharacter used for padding set
39、 by fill member function setfill parameterized stream manipulator Default character is space,21.7.3 Justification (ios:left, ios:right, ios:internal) (II),internal flag Numbers sign left-justified Numbers magnitude right-justified Intervening spaces padded with the fill characterstatic data member i
40、os:adjustfield Contains left, right and internal flags ios:adjustfield must be the second argument to setf when setting the left, right or internal justification flagscout.setf( ios:left, ios:adjustfield);,1. Initialize variable2. Use parameterized stream manipulators3. Output,Program Output,Default
41、 is right justified:12345USING MEMBER FUNCTIONS Use setf to set ios:left: 12345 Use unsetf to restore default:12345USING PARAMETERIZED STREAM MANIPULATORS Use setiosflags to set ios:left: 12345 Use resetiosflags to restore default:12345,21.7.4 Padding (fill, setfill),fill member function Specifies t
42、he fill character Space is default Returns the prior padding charactercout.fill( *);setfill manipulator Also sets fill charactercout setfill (*);,1. Load header1.1 Initialize variable,2. Set fill character3. OutputProgram Output,10000 printed as int right and left justified and as hex with internal
43、justification. Using the default pad character (space):10000 10000 0x 2710Using various padding characters: *10000 10000% 0x2710,21.7.5- Integral Stream Base (ios:dec, ios:oct, ios:hex, ios:showbase),ios:basefield static member Used similarly to ios:adjustfield with setf Includes the ios:oct, ios:he
44、x and ios:dec flag bits Specify that integers are to be treated as octal, hexadecimal and decimal values Default is decimal Default for stream extractions depends on form inputted Integers starting with 0 are treated as octal Integers starting with 0x or 0X are treated as hexadecimal Once a base spe
45、cified, settings stay until changed,21.7.6 Floating-Point Numbers; Scientific Notation (ios:scientific,ios:fixed),ios:scientific Forces output of a floating point number in scientific notation: 1.946000e+009ios:fixed Forces floating point numbers to display a specific number of digits to the right o
46、f the decimal (specified with precision),21.7.6 Floating-Point Numbers; Scientific Notation (II),static data member ios:floatfield Contains ios:scientific and ios:fixed Used similarly to ios:adjustfield and ios:basefield in setf cout.setf(ios:scientific, ios:floatfield); cout.setf(0, ios:floatfield)
47、 restores default format for outputting floating-point numbers,1. Initialize variables2. Set flags3. OutputProgram Output,Displayed in default format: 0.00123457 1.946e+009 Displayed in scientific format: 1.234567e-003 1.946000e+009 Displayed in default format after unsetf: 0.00123457 1.946e+009 Dis
48、played in fixed format: 0.001235 1946000000.000000,21.7.7 Uppercase/Lowercase Control (ios:uppercase),ios:uppercase Forces uppercase E to be output with scientific notation4.32E+010 Forces uppercase X to be output with hexadecimal numbers, and causes all letters to be uppercase75BDE,21.7.8 Setting a
49、nd Resetting the Format Flags (flags, setiosflags, resetiosflags),flags member function Without argument, returns the current settings of the format flags (as a long value) With a long argument, sets the format flags as specified Returns prior settings setf member function Sets the format flags prov
50、ided in its argument Returns the previous flag settings as a long valuelong previousFlagSettings = cout.setf( ios:showpoint | ios:showpos );,setf with two long arguments cout.setf( ios:left, ios:adjustfield ); clears the bits of ios:adjustfield then sets ios:leftThis version of setf can be used with ios:basefield (ios:dec, ios:oct, ios:hex) ios:floatfield (ios:scientific, ios:fixed) ios:adjustfield (ios:left, ios:right, ios:internal ) unsetf Resets specified flags Returns previous settings,