advanced input and output object-oriented programming using c++ second edition 10

67
Advanced Input and Output Advanced Input and Output Object-Oriented Object-Oriented Programming Using C++ Programming Using C++ Second Edition Second Edition 10

Upload: meredith-black

Post on 13-Dec-2015

241 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Advanced Input and OutputAdvanced Input and Output

Object-Oriented Programming Object-Oriented Programming Using C++Using C++

Second EditionSecond Edition

10

Page 2: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

ObjectivesObjectives

• In this chapter, you will learn:

• How cout and cin possess the same traits as other C++ objects

• How to use istream member functions, particularly get(), ignore(), and getline()

• How to use ostream member functions, particularly setf(), unsetf(), width(), and precision()

• How to create your own manipulator functions

10

Page 3: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

ObjectivesObjectives

• In this chapter, you will learn:

• How to use built-in manipulators

• How to create a manipulator that takes an argument

• About computer files and the data hierarchy

• How to perform file output

• How to read a file from within a program

• How to write class objects to files

• How to read a data file into class objects

10

Page 4: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Understanding CIN and Understanding CIN and COUT as Class ObjectsCOUT as Class Objects

• You can think of cout and cin as real-world objects• Like other C++ objects you have created, cout and

cin are members of a class• Their class is derived from another class (which is

derived from yet another class), so they use inheritance

• The cout and cin objects can take advantage of overloaded operators such as << and >> which are used for shifting bits in other contexts

10

Page 5: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Understanding CIN and Understanding CIN and COUT as Class ObjectsCOUT as Class Objects

• When you include iostream.h in a program, you are including a file that contains the definition for a derived class named iostream

• In C++, a stream is a sequence of characters used to perform input and output operations

• The name iostream is short for “Input and Output” stream

10

Page 6: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using istream Member Using istream Member FunctionsFunctions

• In C++, the easiest way to read in a character

is to use cin with the extraction operator, for

example, cin>>someVariable;

• The extraction operator is actually an

overloaded function named operator>>()

10

Page 7: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• Another member function of the istream class is get()

• The get() function takes a character argument and returns a reference to the object (the istream class) that invoked the get() function

• Therefore more than one get() function can be included in a statement

• Its prototype has the following form:istream& get(char &c);

10

Page 8: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• Most compilers overload get() so that, in addition to taking a character reference as an argument, it also can take no argument

• The following version of the get() function returns the character being read in as an integer

• Its prototype is:

int get( );• The third argument is the character that terminates the

entry, often called the delimiter character• The default value to stop data entry, as you can see

from the prototype, is the Enter key, which coded as ‘\n’

10

Page 9: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• The second argument of the get() function—the number of characters to be stored—is very important

• Without the second argument, a user could destroy memory by entering a string of characters that was longer than the area prepared to receive it

• The output in Figure 10-3 and 10-4 illustrate one benefit of using the get() function instead of the extraction operator (>>) for keyboard data entry

10

Ex10-1

Page 10: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• One unfortunate side effect of the get() function is that it leaves unused characters in the input stream

• A subsequent call to get() retrieves the next (unused) character, whether or not that retrieval was intended

• As shown in Figure 10-6, the program doesn’t stop to obtain your grade, because the second call to get() already has been satisfied with the newline character

10

Page 11: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The UserNameAndGrade The UserNameAndGrade ProgramProgram

10

Ex10-2

Page 12: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• The program output shown in Figure 10-6 includes your first name and a newline (instead of a grade) for the letter grade

• To allow the user to enter a grade, you could add a third cin.get() statement to the program, as shown in Figure 10-7

10

Page 13: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• Programmers say this call to the get() function absorbs or consumes the extra character

10

Ex10-2

Page 14: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the get() FunctionUsing the get() Function

• If you run the program in Figure 10-7 and

enter a name that is too long, the output

looks like Figure 10-9

10Ex10-2

Page 15: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the ignore() FunctionUsing the ignore() Function

• It is impossible to guess how many cin.get() statements are needed to consume all the potential additional letters of a name if you use the UserNameAndGrade2 program—imagine the challenge of a name such as Barbara Penelope

• A superior alternative is to use the ignore() function to ignore or skip any additional characters left in the input stream

• The prototype of the ignore() function is:istream& ignore(int length = 1, char c = ‘\n’);

10

Page 16: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The UserNameAndGrade The UserNameAndGrade Program Using ignore()Program Using ignore()

10Ex10-2

Page 17: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the ignore() FunctionUsing the ignore() Function10

Ex10-2

Page 18: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function

• As an alternative to using an extra call to get() to absorb the Enter key after character data entry, or using the ignore() function to absorb any number of characters, you can include another istream member, getline()

• Its prototype is:istream& getline(char *str,int len, char c=‘\n’);

• The getline() function reads a line of text at the address represented by str

• It reads text until it reaches either the length used as the second argument or the character used as the third argument

10

Page 19: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function

• The program in Figure 10-13, and the output in Figure 10-14, show how the getline() function correctly accepts characters up to and including the default newline delimiter

10

Page 20: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function

• When you use a delimiter other than ‘\n’ with getline(), the getline()

consumes the delimiter but leaves he subsequent Enter key in the

input stream, so you still must account for it

• The program in Figure 10-15 and its output in Figure 10-16

illustrate the use of get() to consume the Enter key by getline()

10Ex10-3

Page 21: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function10 Ex10-3

Page 22: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Other istream Member Other istream Member FunctionsFunctions

• Most compilers support other istream member functions with names such as eof(), bad(), and good()

• The istream class is not mysterious

• It is just a class, and cin is just an object that already has been instantiated for you

10

Page 23: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using ostream Member Using ostream Member FunctionsFunctions

• The concepts you have learned while studying the cin object apply to the cout object as well

• The ostream class supports member functions and overloaded operators just like the istream class — or any other class, for that matter

10

Page 24: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using Format Flags with Using Format Flags with setf() and unsetf()setf() and unsetf()

• Many of the states of the cout object are contained in a single long integer field, in which each bit represents some condition of the object

• The arguments that determine the state of the cout object are called format flags or state flags

• All format flags begin with ios::• One member function of the ios class, the setf() function,

takes arguments that set the bits of cout; that is, the arguments turn the bits in the flag on or off

• Another member function, unsetf(), can be used to deselect the bit: cout.unsetf(ios::showpos);

• Using the setf() function, you also can combine format flags using the bitwise OR operator (|)

10

Page 25: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using Format Flags with Using Format Flags with setf() and unsetf()setf() and unsetf()

• Some commonly used format flags are:

– ios::left—left-justifies output within the field size, which may be set by the width() function (described in a following section)

– ios::right—right-justifies output within the field size

– ios::dec—formats numbers in decimal (base 10)

– ios::hex—formats numbers in hexadecimal (base 16)

– ios::oct—formats numbers in octal (base 8)

– ios::showpos—inserts a + before positive numbers

– ios::showpoint—displays the decimal point and six decimal positions for all floating-point numbers

10

Page 26: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the width() FunctionUsing the width() Function

• You can change the output field width with the iostream member width() function

• This function defines the size of the output field in which the passed argument will be displayed

• The width() function applies only to the first subsequent field to be output

10

Page 27: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the width() FunctionUsing the width() Function10

Ex10-4

Page 28: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the precision() Using the precision() FunctionFunction

• You can use the precision() function to control the number of significant digits you see in the output

• If you want to control the number of positions shown to the right of the decimal point (instead of simply the number of significant positions visible), you must combine cout.setf(ios::fixed); and cout.precision();

10

Page 29: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the precision() Using the precision() FunctionFunction

• In the steps outlined on pages 373 and 374 of the textbook, you declare an array of doubles, assign values with different numbers of significant digits, and then display all the values using the same precision

10 Ex10-5

Page 30: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Creating Manipulator Creating Manipulator FunctionsFunctions

• If you need to display a variable named amountMoney in currency format with a dollar sign, in base 10, in a field size of eight, you might write the code shown in Figure 10-20

• When you create a manipulator function, the desired results become much clearer

• A manipulator function is used to manipulate, or change, the state of the cout object

10

Page 31: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Creating Manipulator Creating Manipulator FunctionsFunctions

• You could write a manipulator to format output as currency

• The function contains statements that display the dollar sign, set some ios flags, and set the width

• In the function shown in Figure 10-21, a reference to ostream is passed into the function as an argument

10

Page 32: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using Built-In ManipulatorsUsing Built-In Manipulators

• Some manipulators are so useful that they

are already coded and placed in libraries

included with your C++ compiler

• You already have used the endl manipulator

to output a newline character and flush the

output stream

10

Page 33: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the setprecision() Using the setprecision() ManipulatorManipulator

• You use the setprecision() manipulator to specify the number of decimals that will print

• The setprecision() manipulator works like the precision() function—it specifies the number of significant digits to display

• It is considered a manipulator instead of a member function because you chain a call to setprecision() along with other output and the insertion operator, rather than using an object and a dot operator, as you do with cout.precision()

10

Page 34: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The DemoPrecision2 ProgramThe DemoPrecision2 Program10

Page 35: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the setprecision() Using the setprecision() ManipulatorManipulator

• Any C++ manipulator, such as setprecision(), that takes an argument requires the inclusion of the iomanip.h file in your program

• The program in Figure 10-22 produces the output in Figure 10-23

10 Ex10-6

Page 36: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the setw() ManipulatorUsing the setw() Manipulator

• The setw() manipulator allows you to set the width of a field for output

• Use of the setw() manipulator requires inclusion of the iomanip.h file, because setw() requires an argument that represents the width of the output field

• The setw() manipulator works like the width() member function you can use with the cout objects; the advantage of using setw() is its chaining capability in a cout statement

10

Page 37: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the setiosflags() and Using the setiosflags() and resetiosflags() Manipulatorsresetiosflags() Manipulators

• Two additional manipulators, setiosflags() and resetiosflags(), each perform several manipulations, depending on the flags (such as ios::dec or ios::showpoint) they receive as arguments

• The setiosflags() manipulator turns on bit codes for the attributes named as arguments; the resetiosflags() manipulator turns off those bit codes

10

Page 38: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the setiosflags() and Using the setiosflags() and resetiosflags() Manipulatorsresetiosflags() Manipulators

• In the set of steps shown on pages 379 and 380 of the textbook, you combine the setprecision() and setiosflags() manipulators to produce output that displays decimal values with a fixed number of decimal places in a column

10 Ex10-7

Page 39: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Creating Manipulators that Creating Manipulators that Require an ArgumentRequire an Argument

• To create a manipulator that does not require an argument, you must write a function that receives and returns an ostream reference argument

• To create a manipulator that takes an argument, you must write two functions

• When you use a manipulator that requires no argument, such as endl or the currency manipulator developed above, the address of the output or input stream is passed to the function

• With manipulators, such as setw(), that take an argument both the address of the stream and the argument itself must be passed to the manipulator function

• This task is handled by the omanip() function, which is defined in the file iomanip.h

10

Page 40: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The Currency Manipulator The Currency Manipulator with an Argumentwith an Argument

10

Page 41: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Creating Manipulators that Creating Manipulators that Require an ArgumentRequire an Argument

• In Figure 10-25, the main() program calls the currency function, passing a 7 as the argument that indicates field width

• In the steps referred to on pages 382 and 383 of the textbook, you create a manipulator that formats a part number for a manufacturing company

10 Ex10-8

Page 42: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Creating Manipulators that Creating Manipulators that Require an ArgumentRequire an Argument

10 Ex10-9

Page 43: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

To be continuedTo be continued

• About computer files and the data hierarchy

• How to perform file output

• How to read a file from within a program

• How to write class objects to files

• How to read a data file into class objects

Page 44: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Understanding Computer FilesUnderstanding Computer Files

• When you store data items in a computer system, you use a permanent storage device, such as a disk or a reel of magnetic tape

• The term permanent is used to contrast this type of data storage with the temporary data storage that exists in computer memory

• Data items typically exist in memory for only a short time

• It is common practice to store data in a data hierarchy, which represents the relationships between the sizes of data units that business professionals most often use

10

Page 45: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Understanding Computer FilesUnderstanding Computer Files

• A data field represents one piece of data, such as a first or last name, phone or Social Security number, or salary

• A data record consists of a number of data fields that are logically connected because they pertain to the same entity

• A data file contains records that are logically related

• Often, records within a data file are stored with a space or other delimiting character between fields, and a newline between each record

10

Page 46: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

A Data File Containing A Data File Containing Employee DataEmployee Data

10

Page 47: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Simple File OutputSimple File Output

• You have used a descendant of the ios class— and

its descendant iostream to produce all sorts of

screen output

• In C++, when you write to a disk file rather than to

the screen, you use a class named fstream, which,

like ostream, is ultimately derived from ios

• Figure 10-30 shows the relationship between fstream

and some other input and output classes

10

Page 48: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The fstream Family TreeThe fstream Family Tree10

Page 49: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Simple File OutputSimple File Output

• The fstream class is defined in the fstream.h file, which must be included in any C++ program that writes to or reads from a disk

• You instantiate an ofstream output file object as you do any other object—by calling its constructor

10

Page 50: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Simple File OutputSimple File Output

• In the steps provided on pages 387 to 389 of

the textbook, you open a file write your name

to it, and close it

10

Page 51: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Simple File OutputSimple File Output10 Ex10-10

Page 52: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Simple File InputSimple File Input

• Ifstream and ofstream objects are used in many similar ways

• Like the ofstream class, the name of the ifstream object you instantiate can be any legal C++ identifier; the name has no relationship to the name of the file being opened

• The ifstream class uses the get() function to access file data

• In the steps located on pages 389 and 390 of the textbook, you read the name in from the Name.txt file you created in the previous set of steps

10 Ex10-11

Page 53: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function

• If a file contains data that ends with a newline character, then it’s a bit awkward to have a program that uses the get() function to read data from a file because you must discard the newline character

• As an alternative, you can use the getline() member function to read input data

• The getline() function takes the form fileObject.getline(destination, sizeLimit);, where destination is a declared character string, and sizeLimit is the maximum number of characters you want to store

10

Page 54: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function

• In the list of steps outlined on page 391 of the textbook, you write a program that uses getline() to read the name file created in the WriteNameToFile.cpp program

10Ex10-12

Page 55: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Using the getline() FunctionUsing the getline() Function10 Ex10-13

Page 56: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Writing Objects to FilesWriting Objects to Files

• It is simple and intuitive to use the ofstream class’s overloaded operator to write characters and strings to files

• It makes sense, however, that in object-oriented programs you should also be able to write objects to disk files

• The write() function allows you to do just that; the prototype is:

ostream& write(char *c, int length);

• The write() function accepts two arguments: a pointer to a character and an integer

10

Page 57: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

The Customer ClassThe Customer Class10

Page 58: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Writing Customer Records Writing Customer Records to a Fileto a File

10Ex10-14

Page 59: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Writing Objects to FilesWriting Objects to Files

• You can create an array of customer objects, perform the data entry required for the Customers, and write the output to a disk (see the format on page 394 of the textbook)

• The program in Figure 10-40 executes a for loop numCusts times (five times), performing data entry and writing to the file each time

10

Page 60: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Writing an Array of Customer Writing an Array of Customer Records to a FileRecords to a File

10

Page 61: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Reading Objects from FilesReading Objects from Files

• It is more convenient to read a data file directly into an array of class objects

• You can accomplish this goal with the read() function

• The read() function prototype is quite similar to the prototype for the write() function

• The prototype for read() is:istream& read(char *c, int length);

• The read() function requires a pointer to a character, so you must perform a cast when you read an object

10Ex10-15

Page 62: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Reading Customer Records Reading Customer Records from a Filefrom a File

10

Page 63: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Reading Objects from FilesReading Objects from Files

• The read() function also requires the size of the object being read

• Instead of reading one record at a time into the Customer array, you can perform one read for the entire array

10

Page 64: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

Reading an Array of RecordsReading an Array of Records10

Page 65: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

SummarySummary

• The C++ objects cout and cin possess the same traits as other C++ objects—they are members of a class, use inheritance, have access to overloaded operators, and have all other object traits

• To input data, you can use the extraction operator (>>) after the cin object

• To output data you can use the insertion operator with the cout object

• A manipulator function is used to manipulate, or change, the state of the cout object

10

Page 66: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

SummarySummary

• Built-in manipulators include endl, newline, setprecision(), setw(), setiosflags(), and resetiosflags()

• Creating a manipulator that takes an argument involves writing two functions

• The address of the stream and the argument itself must be passed to the manipulator function

• Usually, you store data on a disk (or other permanent storage device) in a data hierarchy in which fields are parts of data records that make up data files

10

Page 67: Advanced Input and Output Object-Oriented Programming Using C++ Second Edition 10

SummarySummary

• To perform file output, you must instantiate your own member of the ofstream class

• To read a file from within a program, you can create an object that is an instantiation of the ifstream class

• The write() function allows you to write class objects to files

• The write() function accepts two arguments: a character pointer to the address of the argument being written to the file, and the size of the object being written

• You can use the read() function to read a data file into class objects

10