Wrap-Up

Answers to Self Review Exercises

17.1

a) 1s, 0s. b) bit. c) file. d) characters. e) database. f) close. g) get. h) open. i) read. j) seekg, seekp.

17.2
  1. False. Function read can read from any input stream object derived from istream.
  2. False. These four streams are created automatically for the programmer. The header must be included in a file to use them. This header includes declarations for each stream object.
  3. False. The files will be closed when destructors for ifstream, ofstream or fstream objects execute when the stream objects go out of scope or before program execution terminates, but it is a good programming practice to close all files explicitly with close once they are no longer needed.
  4. False. Member function seekp or seekg can be used to reposition the put or get fileposition pointer to the beginning of the file.
  5. True.
  6. False. In most cases, sequential file records are not of uniform length. Therefore, it is possible that updating a record will cause other data to be overwritten.
  7. True.
  8. False. Records in a random-access file normally are of uniform length.
  9. False. It is possible to seek from the beginning of the file, from the end of the file and from the current position in the file.
17.3
  1. ifstream inOldMaster( "oldmast.dat", ios::in );
  2. ifstream inTransaction( "trans.dat", ios::in );
  3. ofstream outNewMaster( "newmast.dat", ios::out);
  4. inOldMaster >> accountNumber >> name >> currentBalance;
  5. inTransaction >> accountNum >> dollarAmount;
  6. outNewMaster << accountNum << name << currentBalance;
17.4
  1. Error: The file payables.dat has not been opened before the attempt is made to output data to the stream.

    Correction: Use ostream function open to open payables.dat for output.

  2. Error: The incorrect istream object is being used to read a record from the file named payables.dat.

    Correction: Use istream object inPayable to refer to payables.dat.

  3. Error: The file's contents are discarded because the file is opened for output (ios::out).

    Correction: To add data to the file, open the file either for updating (ios::ate) or for appending (ios::app).

Exercises

17.5

Fill in the blanks in each of the following:

  1. Computers store large amounts of data on secondary storage devices as__________.
  2. A(n)__________is composed of several fields.
  3. To facilitate the retrieval of specific records from a file, one field in each record is chosen as a__________.
  4. The vast majority of information stored in computer systems is stored in__________files.
  5. A group of related characters that conveys meaning is called a(n)__________.
  6. The standard stream objects declared by header are__________,__________,__________and__________.
  7. ostream member function__________outputs a character to the specified stream.
  8. ostream member function__________is generally used to write data to a randomly accessed file.
  9. istream member function__________repositions the file-position pointer in a file.
17.6

State which of the following are true and which are false. If false, explain why.


  1. The impressive functions performed by computers essentially involve the manipulation of zeros and ones.
  2. People prefer to manipulate bits instead of characters and fields because bits are more compact.
  3. People specify programs and data items as characters; computers then manipulate and process these characters as groups of zeros and ones.
  4. A person's 5-digit zip code is an example of a numeric field.
  5. A person's street address is generally considered to be an alphabetic field in computer applications.
  6. Data items represented in computers form a data hierarchy in which data items become larger and more complex as we progress from fields to characters to bits, etc.
  7. A record key identifies a record as belonging to a particular field.
  8. Most organizations store all information in a single file to facilitate computer processing.
  9. When a program creates a file, the file is automatically retained by the computer for future reference; i.e., files are said to be persistent.
17.7

Exercise 17.3 asked the reader to write a series of single statements. Actually, these statements form the core of an important type of file-processing program, namely, a file-matching program. In commercial data processing, it is common to have several files in each application system. In an accounts-receivable system, for example, there is generally a master file containing detailed information about each customer, such as the customer's name, address, telephone number, outstanding balance, credit limit, discount terms, contract arrangements and, possibly, a condensed history of recent purchases and cash payments.

As transactions occur (e.g., sales are made and cash payments arrive), they are entered into a file. At the end of each business period (a month for some companies, a week for others and a day in some cases), the file of transactions (called trans.dat in Exercise 17.3) is applied to the master file (called oldmast.dat in Exercise 17.3), thus updating each account's record of purchases and payments. During an updating run, the master file is rewritten as a new file (newmast.dat), which is then used at the end of the next business period to begin the updating process again.

File-matching programs must deal with certain problems that do not exist in single-file programs. For example, a match does not always occur. A customer on the master file might not have made any purchases or cash payments in the current business period, and therefore no record for this customer will appear on the transaction file. Similarly, a customer who did make some purchases or cash payments may have just moved to this community, and the company may not have had a chance to create a master record for this customer.

Use the statements from Exercise 17.3 as a basis for writing a complete file-matching accounts-receivable program. Use the account number on each file as the record key for matching purposes. Assume that each file is a sequential file with records stored in increasing order by account number.

When a match occurs (i.e., records with the same account number appear on both the master and transaction files), add the dollar amount on the transaction file to the current balance on the master file, and write the newmast.dat record. (Assume purchases are indicated by positive amounts on the transaction file and payments are indicated by negative amounts.) When there is a master record for a particular account but no corresponding transaction record, merely write the master record to newmast.dat. When there is a transaction record but no corresponding master record, print the error message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record).

17.8

After writing the program of Exercise 17.7, write a simple program to create some test data for checking out the program. Use the following sample account data:

Master file Account number

Name

Balance

100

Alan Jones

348.17

300

Mary Smith

27.19

500

Sam Sharp

0.00

700

Suzy Green

14.22

 

Transaction file Account number

Transaction amount

100

27.14

300

62.11

400

100.56

900

82.17

17.9

Run the program of Exercise 17.7, using the files of test data created in Exercise 17.8. Print the new master file. Check that the accounts have been updated correctly.

17.10

It is possible (actually common) to have several transaction records with the same record key. This occurs because a particular customer might make several purchases and cash payments during a business period. Rewrite your accounts-receivable file-matching program of Exercise 17.7 to provide for the possibility of handling several transaction records with the same record key. Modify the test data of Exercise 17.8 to include the following additional transaction records:

Account number

Dollar amount

300

83.89

700

80.78

700

1.53

17.11

Write a series of statements that accomplish each of the following. Assume that we have defined class Person that contains private data members

char lastName[ 15 ];
char firstName[ 15 ];
char age[ 4 ];
 

and public member functions

// accessor functions for lastName
void setLastName( string );
string getLastName() const;

// accessor functions for firstName
void setFirstName( string );
string getFirstName() const;

// accessor functions for age
void setAge( string );
string getAge() const;
 

Also assume that any random-access files have been opened properly.


  1. Initialize the file nameage.dat with 100 records that store values lastName = "unassigned", firstName = "" and age = "0".
  2. Input 10 last names, first names and ages, and write them to the file.
  3. Update a record that already contains information. If the record does not contain information, inform the user "No info".
  4. Delete a record that contains information by reinitializing that particular record.
17.12

You are the owner of a hardware store and need to keep an inventory that can tell you what different tools you have, how many of each you have on hand and the cost of each one. Write a program that initializes the random-access file hardware.dat to 100 empty records, lets you input the data concerning each tool, enables you to list all your tools, lets you delete a record for a tool that you no longer have and lets you update any information in the file. The tool identification number should be the record number. Use the following information to start your file:

Record#

Tool name

Quantity

Cost

3

Electric sander

7

57.98

17

Hammer

76

11.99

24

Jig saw

21

11.00

39

Lawn mower

3

79.50

56

Power saw

18

99.99

68

Screwdriver

106

6.99

77

Sledge hammer

11

21.50

83

Wrench

34

7.50

17.13

(Telephone Number Word Generator) Standard telephone keypads contain the digits 0 through 9. The numbers 2 through 9 each have three letters associated with them, as is indicated by the following table:

Digit

Letter

2

A B C

3

D E F

4

G H I

5

J K L

6

M N O

7

P R S

8

T U V

9

W X Y

 

Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in the above table to develop the seven-letter word "NUMBERS."

Businesses frequently attempt to get telephone numbers that are easy for their clients to remember. If a business can advertise a simple word for its customers to dial, then no doubt the business will receive a few more calls.


Each seven-letter word corresponds to exactly one seven-digit telephone number. The restaurant wishing to increase its take-home business could surely do so with the number 825-3688 (i.e., "TAKEOUT").

Each seven-digit phone number corresponds to many separate seven-letter words. Unfortunately, most of these represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a barber shop would be pleased to know that the shop's telephone number, 424-7288, corresponds to "HAIRCUT." The owner of a liquor store would, no doubt, be delighted to find that the store's telephone number, 233-7226, corresponds to "BEERCAN." A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters "PETCARE."

Write a C++ program that, given a seven-digit number, writes to a file every possible seven-letter word corresponding to that number. There are 2187 (3 to the seventh power) such words. Avoid phone numbers with the digits 0 and 1.

17.14

Write a program that uses the sizeof operator to determine the sizes in bytes of the various data types on your computer system. Write the results to the file datasize.dat, so that you may print the results later. The results should be displayed in two-column format with the type name in the left column and the size of the type in right column, as in:

 char 1
 unsigned char 1
 short int 2
 unsigned short int 2
 int 4
 unsigned int 4
 long int 4
 unsigned long int 4
 float 4
 double 8
 long double 10
 
 

[Note: The sizes of the built-in data types on your computer might differ from those listed above.]

Introduction to Computers, the Internet and World Wide Web

Introduction to C++ Programming

Introduction to Classes and Objects

Control Statements: Part 1

Control Statements: Part 2

Functions and an Introduction to Recursion

Arrays and Vectors

Pointers and Pointer-Based Strings

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 2

Operator Overloading; String and Array Objects

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

Templates

Stream Input/Output

Exception Handling

File Processing

Class string and String Stream Processing

Web Programming

Searching and Sorting

Data Structures

Bits, Characters, C-Strings and structs

Standard Template Library (STL)

Other Topics

Appendix A. Operator Precedence and Associativity Chart

Appendix B. ASCII Character Set

Appendix C. Fundamental Types

Appendix D. Number Systems

Appendix E. C Legacy Code Topics

Appendix F. Preprocessor

Appendix G. ATM Case Study Code

Appendix H. UML 2: Additional Diagram Types

Appendix I. C++ Internet and Web Resources

Appendix J. Introduction to XHTML

Appendix K. XHTML Special Characters

Appendix L. Using the Visual Studio .NET Debugger

Appendix M. Using the GNU C++ Debugger

Bibliography



C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net