Then do the following: Write a program that uses standard C++ I/O and file I/O in conjunction with data of types employee, manager, fink, and highfink, as defined in Programming Exercise
Trang 1information placed into a string.
Review Questions
.1: What role does the iostream file play in C++ I/O?
.2: Why does typing a number such as 121 as input require a program to make a conversion?
.3: What's the difference between the standard output and the standard error?
.4: Why is cout able to display various C++ types without being provided explicit instructions for each type?
.5: What feature of the output method definitions allows you to concatenate output?
.6: Write a program that requests an integer and then displays it in decimal, octal, and hexadecimal form Display each form on the same line in fields that are 15 characters wide, and use the C++ number base prefixes
.7: Write a program that requests the information shown below and that formats it as shown:
Enter your name: Billy Gruff Enter your hourly wages: 12 Enter number of hours worked: 7.5 First format:
Billy Gruff: $ 12.00: 7.5 Second format:
Billy Gruff : $12.00 :7.5
.8: Consider the following program:
//rq17-8.cpp
#include <iostream>
Trang 2using namespace std;
int main() {
char ch;
int ct1 = 0;
cin >> ch;
while (ch != 'q') {
ct1++;
cin >> ch;
} int ct2 = 0;
cin.get(ch);
while (ch != 'q') {
ct2++;
cin.get(ch);
} cout << "ct1 = " << ct1 << "; ct2 = " << ct2 << "\n";
return 0;
} What does it print, given the following input:
I see a q<Enter>
I see a q<Enter>
Here <Enter> signifies pressing the Enter key
.9: Both of the following statements read and discard characters up to and including the end of a line In what way does the behavior of one differ from that of the other?
while (cin.get() != '\n') continue;
cin.ignore(80, '\n');
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 3Programming Exercises
1: Write a program that counts the number of characters up to the first $ in input and that leaves the $ in the input stream
2: Write a program that copies your keyboard input (up to simulated end-of-file) to a file named on the command line
3: Write a program that copies one file to another Have the program take the filenames from the command line Have the program report if it cannot open
a file
4: Write a program that opens two text files for input and one for output The program concatenates the corresponding lines of the input files, using a space as a separator, and writing the results to the output file If one file is shorter than the other, the remaining lines in the longer file are also copied
to the output file For example, suppose the first input file has these contents:
eggs kites donuts balloons hammers stones
And suppose the second input file has these contents:
zero lassitude finance drama Then the resulting file would have these contents:
eggs kites donuts zero lassitude balloons hammers finance drama stones
5: Mat and Pat want to invite their friends to a party, much as they did in
Chapter 15, "Friends, Exceptions, and More," Programming Exercise 5,
Trang 4except now they want a program that uses files They ask you to write a program that does the following:
Reads a list of Mat's friends' names from a text file called mat.dat, which lists one friend per line The names are stored in a container and then displayed in sorted order
Reads a list of Pat's friends' names from a text file called pat.dat, which lists one friend per line The names are stored in a container and then displayed in sorted order
Merges the two lists, eliminating duplicates, and stores the result in the file matnpat.dat, one friend per line
6: Consider the class definitions of Programming Exercise 13.5 If you haven't yet done that exercise, do so now Then do the following:
Write a program that uses standard C++ I/O and file I/O in conjunction with data of types employee, manager, fink, and highfink, as defined in
Programming Exercise 13.5 The program should be along the general lines
of Listing 17.17 in that it should let you add new data to a file The first time through, the program should solicit data from the user, then show all the entries, then save the information in a file On subsequent uses, the program should first read and display the file data, then let the user add data, then show all the data One difference is that data should be handled
by an array of pointers to type employee That way, a pointer can point to an employee object or to objects of any of the three derived types Keep the array small to facilitate checking the program:
const int MAX = 10; // no more than 10 objects
employee * pc[MAX];
For keyboard entry, the program should use a menu to offer the user the choice of which type of object to create The menu will use a switch to use This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 5new to create an object of the desired type and to assign the object's address to a pointer in the pc array Then that object can use the virtual setall() function to elicit the appropriate data from the user:
pc[i]->setall(); // invokes function corresponding to type of object
To save the data to a file, devise a virtual writeall() function for that purpose:
for (i = 0; i < index; i++) pc[i]->writeall(fout);// fout ofstream connected to output file
Note
Use text I/O, not binary I/O, for this exercise (Unfortunately, virtual objects include pointers to tables of pointers to virtual functions, and write() copies this information to a file An object filled by using read() from the file gets weird values for the function pointers, which really messes up the behavior of virtual functions.) Use a newline to separate each data field from the next; this makes it easier to identify fields on input Or you could still use binary I/O, but not write objects as a whole Instead, you could provide class methods that apply the write() and read() functions to each class member individually rather than to the object as a whole That way, the program can save just the intended data to a file
Trang 6The tricky part is recovering the data from the file The problem is, how can the program know whether the next item to be recovered is an employee object, a manager object, a fink type, or a highfink type? One approach is, when writing the data for an object to a file, precede the data with an integer indicating the type of object to follow Then, on file input, the program can read the integer, then use a switch to create the appropriate object to receive the data:
enum classkind{Employee, Manager, Fink, Highfink}; // in class header
int classtype;
while((fin >> classtype).get(ch)){ // newline separates int from data switch(classtype) {
case Employee : pc[i] = new employee;
: break;
Then you can use the pointer to invoke a virtual getall() function to read the information:
pc[i++]->getall();
CONTENTS
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 7Appendix A NUMBER BASES
Octal Integers Hexadecimal Numbers Binary Numbers
Binary and Hex
Our method for writing numbers is based on powers of 10 For example, consider the
number 2468 The 2 represents 2 thousands, the 4 represents 4 hundreds, the 6
represents 6 tens, and the 8 represents 8 ones:
One thousand is 10x10x10, which can be written as 10[3], or 10 to the 3rd power Using
this notation, we can write the preceding relationship this way:
Because our number notation is based on powers of 10, we refer to it as base 10, or
decimal, notation One can just as easily pick another number as a base C++ lets you use
base 8 (octal) and base 16 (hexadecimal) notation for writing integer numbers (Note: 10[0]
is 1, as is any nonzero number to the zero power.)
Octal Integers
Octal numbers are based on powers of 8, so base 8 notation uses the digits 0–7 in writing
numbers C++ uses a 0 prefix to indicate octal notation Thus, 0177 is an octal value You
can use powers of 8 to find the equivalent base 10 value:
0177 (octal) = 1x8[2] + 7x8[1] + 7x8[0]
= 1x 64 + 7x8 + 7x1
= 127 (decimal)
Trang 8The UNIX operating system often uses octal representation of values, which is why C++
and C provide octal notation
Hexadecimal Numbers
Hexadecimal numbers are based on powers of 16 That means 10 in hexadecimal
represents the value 16 + 0, or 16 To represent the values between 9 and hexadecimal
16, you need a few more digits Standard hexadecimal notation uses the letters a–f for that
purpose C++ accepts either lowercase or uppercase versions of these characters, as
shown in Table A.1
Table A.1 Hexadecimal Digits Hexadecimal digits Decimal value Hexadecimal digits Decimal value
C++ uses a 0x or 0X notation to indicate hexadecimal notation Thus, 0x2B3 is a
hexadecimal value To find its decimal equivalent, you can evaluate the powers of 16:
0x2B3 (hex) = 2x16[2] + 11x16[1] + 3x16[0]
= 2x256 + 11x16 + 3x1
= 691 (decimal)
Hardware documentation often uses hexadecimal notation to represent values such as
memory locations and port numbers
Binary Numbers
Whether you use decimal, octal, or hexadecimal notation for writing an integer, the
computer stores it as a binary, or base 2, value Binary notation uses just two digits, 0 and
1 As an example, 10011011 is a binary number Note, however, that C++ doesn't provide
for writing a number in binary notation Binary numbers are based on powers of 2:
10011011 = 1x2[7] + 0x2[6] + 0x2[5] + 1x2[4] + 1x2[3]
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 9+ 0x2[2] + 1x2[1] + 1x2[0]
= 128 + 0 + 0 + 16 + 8 + 0 + 2 + 1
= 155
Binary notation makes a nice match to computer memory, in which each individual unit,
called a bit, can be set to off or on Just identify the off setting with 0 and the on setting with
1 Memory commonly is organized in units called bytes, with each byte being 8 bits The
bits in a byte are numbered corresponding to the associated power of 2 Thus, the
rightmost bit is bit number 0, the next bit is bit 1, and so on Figure A.1, for example,
represents a 2-byte integer
Figure A.1 A two-byte integer value.
Binary and Hex
Hex notation often is used to provide a more convenient view of binary data, such as
memory addresses or integers holding bit-flag settings The reason is that each
hexadecimal digit corresponds to a four-bit unit Table A.2 shows this correspondence
Trang 10Table A.2 Hexadecimal Digits and Binary Equivalents Hexadecimal digit Binary equivalent Hexadecimal digit Binary equivalent
To convert a hex value to binary, just replace each hex digit by the corresponding binary
equivalent For example, the hex number 0xA4 corresponds to binary 1010 0100 Similarly,
you easily can convert binary values to hex notation by converting each 4-bit unit into the
equivalent hex digit For example, the binary value 1001 0101 becomes 0x95
Real World Note: What Are Big Endian and Little Endian?
Oddly enough, two computing platforms that both use binary representation of integers might not represent the same number identically Intel machines, for example, store bytes using the Little Endian architecture, while Motorola, RISC-based MIPS computers, and the DEC Alpha computers employ the Big Endian scheme
(However, the last two systems can be configured to use either scheme.)
The terms Big Endian and Little Endian are derived from
"Big End In" and "Little End In"—a reference to the order of bytes in a word (typically a two-byte unit) of memory On an Intel computer (Little Endian), the low-order byte is stored first This means a hex value such as 0xABCD would be stored in memory as (0xCD 0xAB) A Motorola (Big Endian) machine would store the same value in the reverse, so 0xABCD would be stored in memory as (0xAB 0xCD)
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 11You, as a software engineer, should understand the word order of the platform you are targeting Among other things, it affects the interpretation of data transmitted over
a network and how data are stored in binary files In the example above, the two-byte memory pattern 0xABCD would represent the decimal value 52,651 on a Little Endian machine and the decimal 43,981 on a Big Endian machine
CONTENTS
Trang 12Appendix B C++ KEYWORDS
Keywords are identifiers that form the vocabulary of a programming language They
may not be used for other purposes, such as serving as a variable name The
following list shows C++'s keywords; not all of them are currently implemented
Keywords shown in boldface are also keywords in the ANSI C99 standard
protected public register reinterpret_cast return
CONTENTS
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 13Appendix C THE ASCII CHARACTER SET
Computers store characters using a numeric code The ASCII code (American
Standard Code for Information Interchange) is the most commonly used code in the
United States C++ lets you represent most single characters directly, by including the
character in single quotation marks, as in 'A' for the A character You can also
represent a single character by using the octal or hex code preceded by a backslash;
for example, '\012' and '\0xa' both represent the linefeed (LF) character Such escape
sequences can also be part of a string, as in "Hello,\012my dear"
When used as a prefix in the following table, the ^ character denotes using a Ctrl key
Trang 1417 021 0x11 00010001 ^Q DC1
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 1547 057 0x2f 00101111 /
Trang 1677 0115 0x4d 01001101 M
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks
Trang 17107 0153 0x6b 01101011 k
127 0177 0x7f 01111111 del, rubout
CONTENTS
Trang 18Appendix D OPERATOR PRECEDENCE
Operator precedence determines the order in which operators are applied to a value
C++ operators come in 18 precedence groups, which are presented in Table D.1
Those in group 1 have the highest precedence, and so on If two operators apply to
the same operand (something upon which an operator operates), the operator with the
higher precedence applies first If the two operators have the same precedence, C++
uses associativity rules to determine which operator binds more tightly All operators in
the same group have the same precedence and the same associativity, which is either
left to right (L–R in the table) or right to left (R–L in the table) Left-to-right associativity
means to apply the left-hand operator first, while right-to-left associativity means to
apply the right-hand operator first
Some symbols, such as * and &, are used for more than one operator In such cases,
one form is unary (one operand) and the other form is binary (two operands), and the
compiler uses the context to determine which is meant The table labels operator
groups unary or binary for those cases in which the same symbol is used two ways
Here are some examples of precedence and associativity:
3 + 5 * 6
The * operator has higher precedence than the + operator, so it is applied to the 5
first, making the expression 3 + 30, or 33
120 / 6 * 5
Both / and * have the same precedence, but these operators associate from left to
right That means the operator to the left of the shared operand (6) is applied first, so
the expression becomes 20 * 5, or 100
char * str = "Whoa";
char ch = *str++;
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks