C++ Stream Input/Output

36
1 C++ Stream Input/Output Chapter 11

description

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 - PowerPoint PPT Presentation

Transcript of C++ Stream Input/Output

Page 1: C++ Stream Input/Output

1

C++ Stream Input/Output

Chapter 11

Page 2: C++ Stream Input/Output

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

Page 3: C++ Stream Input/Output

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

Page 4: C++ Stream Input/Output

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

Page 5: C++ Stream Input/Output

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

Page 6: C++ Stream Input/Output

6

File Class Hierarchy

ios

istream ostream

iostream

ifstream fstream ofstream

iostream.h

fstream.h

InputOutput

File I/O

Multiple inheritanceBase Class

Page 7: C++ Stream Input/Output

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

Page 8: C++ Stream Input/Output

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 <<

Page 9: C++ Stream Input/Output

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;

Page 10: C++ Stream Input/Output

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);

Page 11: C++ Stream Input/Output

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

Page 12: C++ Stream Input/Output

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

Page 13: C++ Stream Input/Output

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)

Page 14: C++ Stream Input/Output

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

Page 15: C++ Stream Input/Output

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

Page 16: C++ Stream Input/Output

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

Page 17: C++ Stream Input/Output

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

Page 18: C++ Stream Input/Output

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

Page 19: C++ Stream Input/Output

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);

Page 20: C++ Stream Input/Output

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

Page 21: C++ Stream Input/Output

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";

Page 22: C++ Stream Input/Output

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

Page 23: C++ Stream Input/Output

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

Page 24: C++ Stream Input/Output

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;

Page 25: C++ Stream Input/Output

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

Page 26: C++ Stream Input/Output

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)

Page 27: C++ Stream Input/Output

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)

Page 28: C++ Stream Input/Output

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)

Page 29: C++ Stream Input/Output

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;

Page 30: C++ Stream Input/Output

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);

Page 31: C++ Stream Input/Output

31

Forms of setf( )

Page 32: C++ Stream Input/Output

32

Uppercase/Lowercase Control

Forces uppercase letters for scientific notation hex notation

Usecout << setiosflags (ios::uppercase) << 1.23e6;

Page 33: C++ Stream Input/Output

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);

Page 34: C++ Stream Input/Output

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( )

Page 35: C++ Stream Input/Output

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

Page 36: C++ Stream Input/Output

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);