1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ Primer Plus (P66) docx

20 324 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

information 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> This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. using 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. Programming 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, This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. except 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. new 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. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. The 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. CONTENTS Appendix 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) This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. The 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 a or A 10 d or D 13 b or B 11 e or E 14 c or C 12 f or F 15 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. + 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. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Table A.2. Hexadecimal Digits and Binary Equivalents Hexadecimal digit Binary equivalent Hexadecimal digit Binary equivalent 0 0000 8 1000 1 0001 9 1001 2 0010 A 1010 3 0011 B 1011 4 0100 C 1100 5 0101 D 1101 6 0110 E 1110 7 0111 F 1111 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. [...]... created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it T CONTENTS Appendix 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... 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... Appendix 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... symbol, such as the unary address operator and the binary bitwise AND operator This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks Table D.1 C++ Operator Precedence and Associativity Precedence Operator 1 :: Scope resolution operator (expression) Grouping 2 () Assoc Meaning L–R Function call () [] Array subscript -> Indirect membership operator... static_cast Specialized type cast typeid Type identification ++ Increment operator, postfix -3 (all unary) Value construction, that is, type (expr) Decrement operator, postfix ! R–L Logical negation ~ + Unary plus (positive sign) - Unary minus (negative sign) ++ Increment operator, prefix Decrement operator, prefix & Address * Dereference (indirect value) () Type cast, that is, (type) expr sizeof Size in . information 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. 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. 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

Ngày đăng: 07/07/2014, 06:20

Xem thêm: C++ Primer Plus (P66) docx

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN