├── .gitignore ├── Appendixes ├── Makefile ├── align.cpp └── memb_pt.cpp ├── Makefile ├── PE ├── ch02 │ ├── 2.1.cpp │ ├── 2.2.cpp │ ├── 2.3.cpp │ ├── 2.4.cpp │ ├── 2.5.cpp │ ├── 2.6.cpp │ └── 2.7.cpp ├── ch03 │ ├── 3.1.cpp │ ├── 3.2.cpp │ ├── 3.3.cpp │ ├── 3.4.cpp │ ├── 3.5.cpp │ ├── 3.6.cpp │ └── 3.7.cpp ├── ch04 │ ├── 4.1.cpp │ ├── 4.10.cpp │ ├── 4.2.cpp │ ├── 4.3.cpp │ ├── 4.4.cpp │ ├── 4.5.cpp │ ├── 4.6.cpp │ ├── 4.7.cpp │ ├── 4.8.cpp │ └── 4.9.cpp ├── ch05 │ ├── 5.1.cpp │ ├── 5.10.cpp │ ├── 5.2.cpp │ ├── 5.3.cpp │ ├── 5.4.cpp │ ├── 5.5.cpp │ ├── 5.6.cpp │ ├── 5.7.cpp │ ├── 5.8.cpp │ └── 5.9.cpp ├── ch06 │ ├── 6.1.cpp │ ├── 6.2.cpp │ ├── 6.3.cpp │ ├── 6.4.cpp │ ├── 6.5.cpp │ ├── 6.6.cpp │ ├── 6.7.cpp │ ├── 6.8.cpp │ └── 6.9.cpp ├── ch07 │ ├── 7.1.cpp │ ├── 7.10.cpp │ ├── 7.2.cpp │ ├── 7.3.cpp │ ├── 7.4.cpp │ ├── 7.5.cpp │ ├── 7.6.cpp │ ├── 7.7.cpp │ ├── 7.8.1.cpp │ ├── 7.8.2.cpp │ └── 7.9.cpp ├── ch08 │ ├── 8.1.cpp │ ├── 8.2.cpp │ ├── 8.3.cpp │ ├── 8.4.cpp │ ├── 8.5.cpp │ ├── 8.6.cpp │ └── 8.7.cpp ├── ch09 │ ├── 9.1 │ │ ├── golf.cpp │ │ ├── golf.h │ │ └── usegolf.cpp │ ├── 9.2.cpp │ ├── 9.3.cpp │ └── 9.4 │ │ ├── sales.cpp │ │ ├── sales.h │ │ └── usesales.cpp ├── ch10 │ ├── 10.1 │ │ ├── account.cpp │ │ ├── account.h │ │ └── useaccount.cpp │ ├── 10.2 │ │ ├── person.cpp │ │ ├── person.h │ │ └── useperson.cpp │ ├── 10.3 │ │ ├── golf.cpp │ │ ├── golf.h │ │ └── usegolf.cpp │ ├── 10.4 │ │ ├── sales.cpp │ │ ├── sales.h │ │ └── usesales.cpp │ ├── 10.5 │ │ ├── stack.cpp │ │ ├── stack.h │ │ └── usestack.cpp │ ├── 10.6 │ │ ├── move.cpp │ │ ├── move.h │ │ └── usemove.cpp │ ├── 10.7 │ │ ├── plorg.cpp │ │ ├── plorg.h │ │ └── useplorg.cpp │ └── 10.8 │ │ ├── Array │ │ ├── list.cpp │ │ ├── list.h │ │ └── uselist.cpp │ │ ├── LinkedList │ │ ├── list.cpp │ │ ├── list.h │ │ └── uselist.cpp │ │ └── Question.txt ├── ch11 │ ├── 11.1 │ │ ├── randwalk.cpp │ │ ├── steps.txt │ │ ├── vect.cpp │ │ └── vect.h │ ├── 11.2 │ │ ├── randwalk.cpp │ │ ├── vect.cpp │ │ └── vect.h │ ├── 11.3 │ │ ├── randwalk.cpp │ │ ├── vect.cpp │ │ └── vect.h │ ├── 11.4 │ │ ├── mytime.cpp │ │ ├── mytime.h │ │ └── usetime.cpp │ ├── 11.5 │ │ ├── stone.cpp │ │ ├── stonewt.cpp │ │ └── stonewt.h │ ├── 11.6 │ │ ├── stone.cpp │ │ ├── stonewt.cpp │ │ └── stonewt.h │ └── 11.7 │ │ ├── complex0.cpp │ │ ├── complex0.h │ │ └── usecomplex.cpp ├── ch12 │ ├── 12.1 │ │ ├── cow.cpp │ │ ├── cow.h │ │ └── usecow.cpp │ ├── 12.2 │ │ ├── pe12_2.cpp │ │ ├── question.txt │ │ ├── string2.cpp │ │ └── string2.h │ ├── 12.3 │ │ ├── stock.cpp │ │ ├── stock.h │ │ └── usestock.cpp │ ├── 12.4 │ │ ├── stack.cpp │ │ ├── stack.h │ │ └── usestack.cpp │ ├── 12.5 │ │ ├── bank.cpp │ │ ├── queue.cpp │ │ └── queue.h │ └── 12.6 │ │ ├── bank.cpp │ │ ├── queue.cpp │ │ └── queue.h ├── ch13 │ ├── 13.1 │ │ ├── cd.h │ │ ├── classic.cpp │ │ ├── classic.h │ │ ├── question.txt │ │ └── useclassic.cpp │ ├── 13.2 │ │ ├── cd.h │ │ ├── classic.cpp │ │ ├── classic.h │ │ └── useclassic.cpp │ ├── 13.3 │ │ ├── dma.cpp │ │ ├── dma.h │ │ └── usedma.cpp │ └── 13.4 │ │ ├── port.cpp │ │ ├── port.h │ │ ├── question.txt │ │ └── test.cpp ├── ch14 │ ├── 14.1 │ │ ├── pair.h │ │ ├── question.txt │ │ ├── usewinec.cpp │ │ ├── winec.cpp │ │ └── winec.h │ ├── 14.2 │ │ ├── pair.h │ │ ├── usewinei.cpp │ │ ├── winei.cpp │ │ └── winei.h │ ├── 14.3 │ │ ├── queuetp.h │ │ ├── workermi.cpp │ │ ├── workermi.h │ │ └── workerqueue.cpp │ ├── 14.4 │ │ ├── person.cpp │ │ ├── person.h │ │ ├── question.txt │ │ └── useperson.cpp │ └── 14.5 │ │ ├── Q&A.txt │ │ ├── emp.cpp │ │ ├── emp.h │ │ └── useemp1.cpp ├── ch15 │ ├── 15.1 │ │ ├── tv.cpp │ │ ├── tv.h │ │ └── usetv.cpp │ ├── 15.2 │ │ ├── 15.2.cpp │ │ └── exc_mean.h │ ├── 15.3 │ │ ├── 15.3.cpp │ │ ├── exc_mean.cpp │ │ └── exc_mean.h │ └── 15.4 │ │ ├── 15.4.cpp │ │ ├── sales.cpp │ │ └── sales.h ├── ch16 │ ├── 16.1.cpp │ ├── 16.10.cpp │ ├── 16.2.cpp │ ├── 16.3.cpp │ ├── 16.4.cpp │ ├── 16.5.cpp │ ├── 16.6.cpp │ ├── 16.7.cpp │ ├── 16.8.cpp │ ├── 16.9.cpp │ └── wordlist.txt ├── ch17 │ ├── 17.1.cpp │ ├── 17.2.cpp │ ├── 17.3.cpp │ ├── 17.4.cpp │ ├── 17.5.cpp │ ├── 17.6 │ │ ├── emp.cpp │ │ ├── emp.h │ │ ├── question.txt │ │ └── useemp.cpp │ └── 17.7.cpp └── ch18 │ ├── 18.1.cpp │ ├── 18.2.cpp │ ├── 18.3.cpp │ └── 18.4.cpp ├── ch02 ├── Makefile ├── carrot.cpp ├── convert.cpp ├── getinfo.cpp ├── myfirst.cpp ├── ourfunc.cpp └── sqrt.cpp ├── ch03 ├── Makefile ├── arith.cpp ├── bondini.cpp ├── chartype.cpp ├── divide.cpp ├── exceed.cpp ├── floatnum.cpp ├── fltadd.cpp ├── hexoct1.cpp ├── hexoct2.cpp ├── init.cpp ├── limits.cpp ├── modulus.cpp ├── morechar.cpp └── typecast.cpp ├── ch04 ├── Makefile ├── addpntrs.cpp ├── address.cpp ├── arraynew.cpp ├── arrayone.cpp ├── arrstruc.cpp ├── assgn_st.cpp ├── choices.cpp ├── delete.cpp ├── init_ptr.cpp ├── instr1.cpp ├── instr2.cpp ├── instr3.cpp ├── mixtypes.cpp ├── newstrct.cpp ├── numstr.cpp ├── pointer.cpp ├── ptrstr.cpp ├── strings.cpp ├── strtype1.cpp ├── strtype2.cpp ├── strtype3.cpp ├── strtype4.cpp ├── structur.cpp └── use_new.cpp ├── ch05 ├── Makefile ├── bigstep.cpp ├── block.cpp ├── compstr1.cpp ├── compstr2.cpp ├── dowhile.cpp ├── equal.cpp ├── express.cpp ├── forloop.cpp ├── formore.cpp ├── forstr1.cpp ├── forstr2.cpp ├── nested.cpp ├── num_test.cpp ├── plus_one.cpp ├── textin1.cpp ├── textin2.cpp ├── textin3.cpp ├── textin4.cpp ├── waiting.cpp └── while.cpp ├── ch06 ├── Makefile ├── and.cpp ├── carinfo.txt ├── cctypes.cpp ├── cinfish.cpp ├── cingolf.cpp ├── condit.cpp ├── enum.cpp ├── if.cpp ├── ifelse.cpp ├── ifelseif.cpp ├── jump.cpp ├── more_and.cpp ├── not.cpp ├── or.cpp ├── outfile.cpp ├── scores.txt ├── sumafile.cpp └── switch.cpp ├── ch07 ├── Makefile ├── arfupt.cpp ├── arrfun1.cpp ├── arrfun2.cpp ├── arrfun3.cpp ├── arrfun4.cpp ├── arrobj.cpp ├── atrcfun.cpp ├── calling.cpp ├── fun_ptr.cpp ├── lotto.cpp ├── protos.cpp ├── recur.cpp ├── ruler.cpp ├── strctptr.cpp ├── strgback.cpp ├── strgfun.cpp ├── topfive.cpp ├── travel.cpp └── twoarg.cpp ├── ch08 ├── Makefile ├── choices.cpp ├── cubes.cpp ├── ep-data.txt ├── filefunc.cpp ├── firstref.cpp ├── funtemp.cpp ├── inline.cpp ├── left.cpp ├── leftover.cpp ├── secref.cpp ├── strc_ref.cpp ├── strquote.cpp ├── swaps.cpp ├── tempover.cpp ├── twoswap.cpp └── twotemps.cpp ├── ch09 ├── Makefile ├── autoscp.cpp ├── coordin.h ├── external.cpp ├── file1.cpp ├── file2.cpp ├── namesp.cpp ├── namesp.h ├── newplace.cpp ├── static.cpp ├── support.cpp ├── twofile1.cpp ├── twofile2.cpp └── usenmsp.cpp ├── ch10 ├── Makefile ├── stack.cpp ├── stack.h ├── stacker.cpp ├── stock00.cpp ├── stock00.h ├── stock10.cpp ├── stock10.h ├── stock20.cpp ├── stock20.h ├── stuff ├── usestock0.cpp ├── usestock1.cpp └── usestock2.cpp ├── ch11 ├── Makefile ├── mytime0.cpp ├── mytime0.h ├── mytime1.cpp ├── mytime1.h ├── mytime2.cpp ├── mytime2.h ├── mytime3.cpp ├── mytime3.h ├── randwalk.cpp ├── stone.cpp ├── stone1.cpp ├── stonewt.cpp ├── stonewt.h ├── stonewt1.cpp ├── stonewt1.h ├── usetime0.cpp ├── usetime1.cpp ├── usetime2.cpp ├── usetime3.cpp ├── vect.cpp └── vect.h ├── ch12 ├── Makefile ├── bank.cpp ├── placenew1.cpp ├── placenew2.cpp ├── queue.cpp ├── queue.h ├── sayings1.cpp ├── sayings2.cpp ├── string1.cpp ├── string1.h ├── strngbad.cpp ├── strngbad.h └── vegnews.cpp ├── ch13 ├── Makefile ├── acctabc.cpp ├── acctabc.h ├── brass.cpp ├── brass.h ├── dma.cpp ├── dma.h ├── tabtenn0.cpp ├── tabtenn0.h ├── tabtenn1.cpp ├── tabtenn1.h ├── usebrass1.cpp ├── usebrass2.cpp ├── usebrass3.cpp ├── usedma.cpp ├── usett0.cpp └── usett1.cpp ├── ch14 ├── Makefile ├── arraytp.h ├── frnd2tmp.cpp ├── manyfrnd.cpp ├── pairs.cpp ├── stacktem.cpp ├── stacktp.h ├── stcktp1.h ├── stkoptr1.cpp ├── studentc.cpp ├── studentc.h ├── studenti.cpp ├── studenti.h ├── tempmemb.cpp ├── tempparm.cpp ├── tmp2tmp.cpp ├── twod.cpp ├── use_stuc.cpp ├── use_stui.cpp ├── worker0.cpp ├── worker0.h ├── workermi.cpp ├── workermi.h ├── workmi.cpp └── worktest.cpp ├── ch15 ├── Makefile ├── constcast.cpp ├── error1.cpp ├── error2.cpp ├── error3.cpp ├── error4.cpp ├── error5.cpp ├── exc_mean.h ├── nested.cpp ├── newexcp.cpp ├── queuetp.h ├── rtti1.cpp ├── rtti2.cpp ├── sales.cpp ├── sales.h ├── tv.cpp ├── tv.h ├── tvfm.h ├── use_sales.cpp └── use_tv.cpp ├── ch16 ├── Makefile ├── copyit.cpp ├── fowl.cpp ├── funadap.cpp ├── functor.cpp ├── hangman.cpp ├── ilist.cpp ├── inserts.cpp ├── list.cpp ├── listrmv.cpp ├── multmap.cpp ├── setops.cpp ├── smrtptrs.cpp ├── str1.cpp ├── str2.cpp ├── strfile.cpp ├── strgst1.cpp ├── tobuy.txt ├── usealgo.cpp ├── valvect.cpp ├── vect1.cpp ├── vect2.cpp ├── vect3.cpp └── vslice.cpp ├── ch17 ├── Makefile ├── append.cpp ├── binary.cpp ├── check_it.cpp ├── cinexcp.cpp ├── count.cpp ├── defaults.cpp ├── fileio.cpp ├── fill.cpp ├── get_fun.cpp ├── guests.txt ├── iomanip.cpp ├── manip.cpp ├── peeker.cpp ├── planets.dat ├── precise.cpp ├── pythag ├── random.cpp ├── setf.cpp ├── setf2.cpp ├── showpt.cpp ├── strin.cpp ├── strout.cpp ├── truncate.cpp ├── width.cpp └── write.cpp ├── ch18 ├── Makefile ├── callable.cpp ├── lambda0.cpp ├── lambda1.cpp ├── lexcast.cpp ├── rvref.cpp ├── somedefs.h ├── stdmove.cpp ├── useless.cpp ├── variadic1.cpp ├── variadic2.cpp └── wrapped.cpp ├── clang++Warning.txt ├── g++Warning.txt ├── list.txt └── readme.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | 30 | # Temp files 31 | *~ 32 | *.tmp 33 | 34 | # Shell scripts 35 | *.sh 36 | 37 | # Backup files 38 | *.bak 39 | 40 | # YouCompleteMe Settings 41 | .ycm_extra_conf.py 42 | .ycm_extra_conf.pyc 43 | -------------------------------------------------------------------------------- /Appendixes/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | .PHONY: all 3 | all : align memb_pt 4 | align: align.o 5 | $(CXX) -o align align.o 6 | memb_pt: memb_pt.o 7 | $(CXX) -o memb_pt memb_pt.o 8 | 9 | 10 | align.o: align.cpp 11 | $(CXX) -c align.cpp -std=c++11 12 | memb_pt.o: memb_pt.cpp 13 | $(CXX) -c memb_pt.cpp 14 | .PHONY: cleanobj 15 | cleanobj: 16 | rm -f *.o 17 | 18 | .PHONY: clean 19 | clean: 20 | find . -maxdepth 1 -type f -perm /111 -exec rm {} \; 21 | rm -f *.o 22 | -------------------------------------------------------------------------------- /Appendixes/align.cpp: -------------------------------------------------------------------------------- 1 | // align.cpp -- checking alignment 2 | #include 3 | using namespace std; 4 | struct things1 5 | { 6 | char ch; 7 | int a; 8 | double x; 9 | }; 10 | 11 | struct things2 12 | { 13 | int a; 14 | double x; 15 | char ch; 16 | }; 17 | 18 | int main() 19 | { 20 | things1 th1; 21 | things2 th2; 22 | cout << "char alignment: " << alignof(char) << endl; 23 | cout << "int alignment: " << alignof(int) << endl; 24 | cout << "double alignment: " << alignof(double) << endl; 25 | cout << "things1 alignment: " << alignof(things1) << endl; 26 | cout << "things2 alignment: " << alignof(things2) << endl; 27 | cout << "things1 size: " << sizeof(things1) << endl; 28 | cout << "things2 size: " << sizeof(things2) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SUBDIRS=ch02 ch03 ch04 ch05 ch06 ch07 ch08 ch09 ch10 ch11 ch12 ch13 ch14 ch15 ch16 ch17 ch18 Appendixes 2 | define make_subdir 3 | @for subdir in $(SUBDIRS) ; do \ 4 | ( cd $$subdir && make $1) \ 5 | done; 6 | endef 7 | all: 8 | $(call make_subdir , all) 9 | cleanobj: 10 | $(call make_subdir , cleanobj) 11 | clean: 12 | $(call make_subdir , clean) 13 | -------------------------------------------------------------------------------- /PE/ch02/2.1.cpp: -------------------------------------------------------------------------------- 1 | // Write a C++ program that displays your name and address (or if you value 2 | // your privacy, a fictitious name and address). 3 | // 4 | // Here, name is John, address is Wuhan University. 5 | #include 6 | 7 | int main(void) 8 | { 9 | using namespace std; 10 | 11 | cout << "Name: John" << endl; 12 | cout << "Address: Wuhan University" << endl; 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /PE/ch02/2.2.cpp: -------------------------------------------------------------------------------- 1 | // Write a C++ program that asks for a distance in furlongs and converts it 2 | // to yards. (One furlong is 220 yards.) 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | int furlong, yard; 9 | 10 | cout << "Enter a distance in furlongs: "; 11 | cin >> furlong; 12 | yard = furlong * 220; 13 | cout << furlong << " furlong = " << yard << " yards." << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /PE/ch02/2.3.cpp: -------------------------------------------------------------------------------- 1 | // Write a C++ program that uses three user-defined functions (counting 2 | // main() as one) and produces the following output: 3 | // Three blind mice 4 | // Three blind mice 5 | // See how they run 6 | // See how they run 7 | // One function, called two times, should produce the first two lines, and 8 | // the remaining function, also called twice, should produce the remaining 9 | // output. 10 | #include 11 | using namespace std; 12 | 13 | void func1(); 14 | void func2(); 15 | int main() 16 | { 17 | func1(); 18 | func1(); 19 | func2(); 20 | func2(); 21 | 22 | return 0; 23 | } 24 | 25 | void func1() 26 | { 27 | cout << "Three blind mice" << endl; 28 | } 29 | 30 | void func2() 31 | { 32 | cout << "See how they run" << endl; 33 | } 34 | -------------------------------------------------------------------------------- /PE/ch02/2.4.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that asks the user to enter his or her age. The program 2 | // then should display the age in months: 3 | // Enter your age: 29 4 | // Your age in months is 348. 5 | #include 6 | 7 | int main() 8 | { 9 | using namespace std; 10 | 11 | int age; 12 | cout << "Enter your age: "; 13 | cin >> age; 14 | cout << "Your age in months is " << age * 12 << "." << endl; 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /PE/ch02/2.5.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that has main() call a user-defined function that takes 2 | // a Celsius temperature value as an argument and then returns the 3 | // equivalent Fahrenheit value. The program should request the Celsius value 4 | // as input from the user and display the result, as shown in the following 5 | // code: 6 | // Please enter a Celsius value: 20 7 | // 20 degrees Celsius is 68 degrees Fahreheit. 8 | // For reference, here is the formula for making the conversion: 9 | // Fahrenheit = 1.8 * degrees Celsius + 32.0 10 | #include 11 | 12 | double CtoF(double celsius); 13 | int main() 14 | { 15 | using namespace std; 16 | 17 | double celsius, fahrenheit; 18 | cout << "Please enter a Celsius value: "; 19 | cin >> celsius; 20 | fahrenheit = CtoF(celsius); 21 | cout << celsius << " degrees Celsius is " 22 | << fahrenheit << " degrees Fahrenheit." << endl; 23 | 24 | return 0; 25 | } 26 | 27 | double CtoF(double celsius) 28 | { 29 | return 1.8 * celsius + 32.0; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch02/2.7.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that asks the user to enter an hour value and a minute 2 | // value. The main() function should then pass these two values to a type 3 | // void function that displays the two values in the format shown in the 4 | // following sample run: 5 | // Enter the number of hours: 9 6 | // Enter the number of minutes: 28 7 | // Time: 9:28 8 | #include 9 | 10 | void show_time(int hour, int minute); 11 | int main() 12 | { 13 | using namespace std; 14 | 15 | int hour, minute; 16 | cout << "Enter the number of hours: "; 17 | cin >> hour; 18 | cout << "Enter the number of minutes: "; 19 | cin >> minute; 20 | show_time(hour, minute); 21 | 22 | return 0; 23 | } 24 | 25 | void show_time(int hour, int minute) 26 | { 27 | using namespace std; 28 | 29 | cout << "Time: " << hour << ":" << minute << endl; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch03/3.1.cpp: -------------------------------------------------------------------------------- 1 | // Write a short program that asks for your height in integer inches and 2 | // then converts your height to feet and inches. Have the program use the 3 | // underscore character to indicate where to type the response. Also use a 4 | // const symbolic constant to represent the conversion factor. 5 | #include 6 | 7 | int main() 8 | { 9 | using namespace std; 10 | 11 | const int Inch_to_feet = 12; 12 | int height; 13 | cout << "Please enter your height in inches: __\b\b"; 14 | cin >> height; 15 | int feet, inches; 16 | feet = height / Inch_to_feet; 17 | inches = height % Inch_to_feet; 18 | cout << height << " inches is "; 19 | cout << feet << " feet, " << inches << " inches." << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /PE/ch03/3.7.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that asks you to enter an automobile gasoline consumption 3 | * figure in the European style (liters per 100 kilometers) and converts to 4 | * the U.S. style of miles per gallon. Note that in addition to using 5 | * different units of measurement, the U.S. approach (distance / fuel) is 6 | * the inverse of the European approach (fuel / distance). Note that 100 7 | * kilometers is 62.14 miles, and 1 gallon is 3.875 liters. Thus, 19 mpg is 8 | * about 12.4 L/100km, and 27 mpg is about 8.7 L/100km. 9 | */ 10 | #include 11 | 12 | int main() 13 | { 14 | using namespace std; 15 | double mpg, lphkm; // lphkm means Liters Per Hundred KiloMeters 16 | const double Miles_per_100_km = 62.14; 17 | const double Liters_per_gallon = 3.875; 18 | 19 | cout << "Enter the automobile gasoline consumption figure" 20 | << " in L/100km: "; 21 | cin >> lphkm; 22 | mpg = 1 / (lphkm / Liters_per_gallon / Miles_per_100_km); 23 | cout << lphkm << " L/100km = " << mpg << " mpg." << endl; 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /PE/ch04/4.10.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that requests the user to enter three times for the 3 | * 40-yd dash (or 40-meter, if you prefer) and then displays the times and 4 | * the average. Use an array object to hold the data. (Use a built-in array 5 | * if array is not available.) 6 | */ 7 | #include 8 | #include 9 | int main() 10 | { 11 | using namespace std; 12 | array time; 13 | // if your compiler doesn't support C++11, use double time[3]; 14 | cout << "Please enter the first time for the 40-yd dash: "; 15 | cin >> time[0]; 16 | cout << "Please enter the second time for the 40-yd dash: "; 17 | cin >> time[1]; 18 | cout << "Please enter the third time for the 40-yd dash: "; 19 | cin >> time[2]; 20 | 21 | double average = (time[0] + time[1] + time[2]) / 3; 22 | 23 | cout << "The 1st: " << time[0] << " s\n"; 24 | cout << "The 2nd: " << time[1] << " s\n"; 25 | cout << "The 3rd: " << time[2] << " s\n"; 26 | cout << "The average: " << average << " s\n"; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /PE/ch04/4.2.cpp: -------------------------------------------------------------------------------- 1 | // Rewrite Listing 4.4, using the C++ string class instead of char arrays. 2 | #include 3 | #include 4 | int main() 5 | { 6 | using namespace std; 7 | string name; 8 | string dessert; 9 | 10 | cout << "Enter your name:\n"; 11 | getline(cin, name); // reads through newline 12 | cout << "Enter your favorite dessert:\n"; 13 | getline(cin, dessert); 14 | cout << "I have some delicious " << dessert; 15 | cout << " for you, " << name << ".\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /PE/ch04/4.4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that asks the user to enter his or her first name and 3 | * then last name, and that then constructs, stores, and displays a third 4 | * string consisting of the user's last name followed by a comma, a space, 5 | * and first name. Use string objects and methods from the string header 6 | * file. A sample run could look like this: 7 | * Enter your first name: Flip 8 | * Enter your last name: Fleming 9 | * Here's the information in a single string: Fleming, Flip 10 | */ 11 | #include 12 | #include 13 | int main() 14 | { 15 | using namespace std; 16 | string fname, lname; 17 | string complete_name; 18 | cout << "Enter your first name: "; 19 | getline(cin, fname); 20 | cout << "Enter your last name: "; 21 | cin >> lname; 22 | complete_name = lname + ", " + fname; 23 | cout << "Here's the information in a single string: " 24 | << complete_name << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /PE/ch04/4.8.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Do Programming Exercise 7 but use new to allocate a structure instead of 3 | * declaring a structure varaible. Also have the program request the pizza 4 | * diameter before it requests the pizza company name. 5 | */ 6 | #include 7 | struct Pizza 8 | { 9 | char name[40]; 10 | double diameter; 11 | double weight; 12 | }; 13 | int main() 14 | { 15 | using namespace std; 16 | Pizza * ptr = new Pizza; 17 | cout << "Enter the diameter of the pizza: "; 18 | cin >> ptr->diameter; 19 | cin.get(); 20 | cout << "Enter the name of the pizza company: "; 21 | cin.getline(ptr->name, 40); 22 | cout << "Enter the weight of the pizza: "; 23 | cin >> ptr->weight; 24 | 25 | cout << "The information of the pizza:\n"; 26 | cout << "Company name: " << ptr->name << endl; 27 | cout << "Diameter: " << ptr->diameter << endl; 28 | cout << "Weight: " << ptr->weight << endl; 29 | delete ptr; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /PE/ch05/5.1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that requests the user to enter two integers. The program 3 | * should then calculate and report the sum of all the integers between and 4 | * including the two integers. At this point, assume that the smaller 5 | * integer is entered first. For example, if the user enters 2 and 9, the 6 | * program should report that the sum of all the integers from 2 through 9 7 | * is 44. 8 | */ 9 | #include 10 | int main() 11 | { 12 | using namespace std; 13 | int begin, end; 14 | cout << "Enter the first number: "; 15 | cin >> begin; 16 | cout << "Enter the second number, larger than the first one: "; 17 | cin >> end; 18 | int sum = 0; 19 | for (int i = begin; i <= end; i++) 20 | sum += i; 21 | cout << "The sum of the integers from " << begin << " through " 22 | << end << " is " << sum << ".\n"; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /PE/ch05/5.10.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program using nested loops that asks the user to enter a value 3 | * for the number of rows to display. It should then display that many rows 4 | * of asterisks, with one asterisk in the first row, two in the second row, 5 | * and so on. For each row, the asterisks are preceded by the number of 6 | * periods needed to make all the rows display a total number of characters 7 | * equal to the number of rows. A sample run would look like this: 8 | * Enter number of rows: 5 9 | * ....* 10 | * ...** 11 | * ..*** 12 | * .**** 13 | * ***** 14 | */ 15 | #include 16 | int main() 17 | { 18 | using namespace std; 19 | int row; 20 | cout << "Enter number of rows: "; 21 | cin >> row; 22 | for (int i = 0; i < row; i++) 23 | { 24 | for (int j = 1; j < row - i; j++) 25 | cout << '.'; 26 | for (int k = 0; k <= i; k++) 27 | cout << '*'; 28 | cout << '\n'; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /PE/ch05/5.2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Redo Listing 5.4 using a type array object instead of a buit-in array 3 | * and type long double instead of long long. Find the value of 100! 4 | */ 5 | #include 6 | #include 7 | const int ArSize = 101; // example of external declaration 8 | int main() 9 | { 10 | using namespace std; 11 | array factorials; 12 | factorials[1] = factorials[0] = 1; 13 | for (int i = 2; i < ArSize; i++) 14 | factorials[i] = i * factorials[i-1]; 15 | for (int i = 0; i < ArSize; i++) 16 | cout << i << "! = " << factorials[i] << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /PE/ch05/5.3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that asks the user to type in numbers. After each entry, 3 | * the program should report the cumulative sum of the entries to date. The 4 | * program should terminate when the user enters 0. 5 | */ 6 | #include 7 | int main() 8 | { 9 | using namespace std; 10 | double input; 11 | double sum = 0.0; 12 | cout << "Please enter a number, 0 to quit: "; 13 | cin >> input; 14 | while (input != 0.0) 15 | { 16 | sum += input; 17 | cout << "The cumulative sum of the entries to date is "; 18 | cout << sum << endl; 19 | cout << "Continue entering numbers: "; 20 | cin >> input; 21 | } 22 | cout << "Done.\n"; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /PE/ch05/5.8.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that uses an array of char and a loop to read one word 3 | * at a time until the word done is entered. The program should then report 4 | * the number of words entered (not counting done). A sample run could look 5 | * like this: 6 | * Enter words (to stop, type the word done): 7 | * anteater birthday category dumpster 8 | * envy finagle geometry done for sure 9 | * You entered a total of 7 words. 10 | * You should include the cstring header file and use the srecmp() function 11 | * to make the comparision test. 12 | */ 13 | #include 14 | #include 15 | int main() 16 | { 17 | using namespace std; 18 | int count = 0; 19 | char word[40]; 20 | cout << "Enter words (to stop, type the word done): " << endl; 21 | cin >> word; 22 | while (strcmp(word, "done")) 23 | { 24 | count++; 25 | cin >> word; 26 | } 27 | cout << "You entered a total of " << count << " words.\n"; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch05/5.9.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that matches the description of the program in 3 | * Programming Exercise 8, but use a string class object instead of an 4 | * array. Include the string header file and use a relational operator to 5 | * make the comparison test. 6 | */ 7 | #include 8 | #include 9 | int main() 10 | { 11 | using namespace std; 12 | int count = 0; 13 | string word; 14 | cout << "Enter words (to stop, type the word done):\n"; 15 | cin >> word; 16 | while (word != "done") 17 | { 18 | count++; 19 | cin >> word; 20 | } 21 | cout << "You entered a total of " << count << " words.\n"; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /PE/ch06/6.1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that reads keyboard input to the @ symbol and that echoes 3 | * the input except for digits, converting each uppercase character to 4 | * lowercase, and vice versa. (Don't forget the cctype family.) 5 | */ 6 | #include 7 | #include 8 | int main() 9 | { 10 | using namespace std; 11 | char ch; 12 | cout << "Enter characters; enter @ to quit:\n"; 13 | cin.get(ch); 14 | while (ch != '@') 15 | { 16 | if (!isdigit(ch)) 17 | { 18 | if (islower(ch)) 19 | cout << char (toupper(ch)); 20 | else if (isupper(ch)) 21 | cout << char (tolower(ch)); 22 | else 23 | cout << ch; 24 | } 25 | cin.get(ch); 26 | } 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /PE/ch06/6.8.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that opens a text file, reads it character-by-character 3 | * to the end of the file, and reports the number of characters in the file. 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | int main() 10 | { 11 | using namespace std; 12 | char filename[80]; 13 | cout << "Enter the name of text file: "; 14 | cin.getline(filename, 80); 15 | ifstream inFile; 16 | inFile.open(filename); 17 | if (!inFile.is_open()) 18 | { 19 | cout << "Could not open the file " << filename << endl; 20 | cout << "Program terminated.\n"; 21 | exit(EXIT_FAILURE); 22 | } 23 | int count = 0; 24 | int ch; 25 | 26 | while ((ch = inFile.get()) != EOF) 27 | count++; 28 | cout << "There are " << count << " characters in this file.\n"; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch07/7.1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program that repeatedly asks the user to enter pairs of numbers 3 | * until at least one of the pair is 0. For each pair, the program should 4 | * use a function to calculate the harmonic mean of the numbers. The 5 | * function should return the answer to main(), which should report the 6 | * result. The harmonic mean of the numbers is the inverse of the average 7 | * of the inverses and can be calculated as follows: 8 | * harmonic mean = 2.0 * x * y / (x + y) 9 | */ 10 | #include 11 | double hmean(double, double); 12 | int main() 13 | { 14 | using namespace std; 15 | double num1, num2; 16 | cout << "Enter two numbers, enter 0 to quit: "; 17 | while (cin >> num1 >> num2 && num1 != 0 && num2 != 0) 18 | { 19 | double result = hmean(num1, num2); 20 | cout << "The harmonic mean of " << num1 << " and " << num2 21 | << " is " << result << endl; 22 | cout << "Enter next pair: "; 23 | } 24 | cout << "Bye!\n"; 25 | return 0; 26 | } 27 | double hmean(double x, double y) 28 | { 29 | return 2.0 * x * y / (x + y); 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch07/7.5.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Define a recursive function that takes an integer argument and returns 3 | * the factorial of that argument. Recall that 3 factorial, written 3!, 4 | * equals 3 * 2!, and so on, with 0! defined as 1. In general, if n is 5 | * greater than zero, n! = n * (n-1)!. Test your function in a program that 6 | * uses a loop to allow the user to enter various values for which the 7 | * program reports the factorial. 8 | */ 9 | #include 10 | long double factorial(int n); 11 | int main() 12 | { 13 | using namespace std; 14 | int n; 15 | cout << "Please enter an integer: "; 16 | while ((cin >> n) && n >= 0) 17 | { 18 | cout << n << "! = " << factorial(n) << endl; 19 | cout << "Next integer, q to quit: "; 20 | } 21 | cout << "Bye!\n"; 22 | return 0; 23 | } 24 | 25 | long double factorial(int n) 26 | { 27 | long double result; 28 | if (n == 0) 29 | result = 1.0; 30 | else 31 | result = n * factorial(n-1); 32 | return result; 33 | } 34 | -------------------------------------------------------------------------------- /PE/ch07/7.8.2.cpp: -------------------------------------------------------------------------------- 1 | // Program Exercise 8 in Unit 7, and this is the method B. 2 | #include 3 | // constant data 4 | const int Seasons = 4; 5 | const char * Snames[Seasons] = 6 | {"Spring", "Summer", "Fall", "Winter"}; 7 | struct array 8 | { 9 | double a[Seasons]; 10 | }; 11 | 12 | void fill(array * pa); 13 | void show(array da); 14 | 15 | int main() 16 | { 17 | array expenses; 18 | fill(&expenses); 19 | show(expenses); 20 | return 0; 21 | } 22 | 23 | void fill(array * pa) 24 | { 25 | using namespace std; 26 | for (int i = 0; i < Seasons; i++) 27 | { 28 | cout << "Enter " << Snames[i] << " expenses: "; 29 | cin >> pa->a[i]; 30 | } 31 | } 32 | 33 | void show(array da) 34 | { 35 | using namespace std; 36 | double total = 0.0; 37 | cout << "\nEXPENSES\n"; 38 | for (int i = 0; i < Seasons; i++) 39 | { 40 | cout << Snames[i] << ": $" << da.a[i] << endl; 41 | total += da.a[i]; 42 | } 43 | cout << "Total expenses: $" << total << endl; 44 | } 45 | -------------------------------------------------------------------------------- /PE/ch08/8.5.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a template function max5() that takes as its argument an array of 3 | * five items of type T and returns the largest item in the array. (Because 4 | * the size is fixed, it can be hard-coded into the loop instead of being 5 | * passed as an argument.) Test it in a program that uses the function with 6 | * an array of five int value and an value of five double values. 7 | */ 8 | #include 9 | template 10 | T max5(T arr[]); 11 | 12 | int main(void) 13 | { 14 | using namespace std; 15 | int arr_int[5] = {73, 59, 88, 11, 95}; 16 | double arr_dbl[5] = {48.02, 15.78, 10.65, 51.52, 17.21}; 17 | cout << "The maximum of arr_int[5]: " << max5(arr_int) << endl; 18 | cout << "The maximum of arr_dbl[5]: " << max5(arr_dbl) << endl; 19 | return 0; 20 | } 21 | 22 | template 23 | T max5(T arr[]) 24 | { 25 | T tmax = arr[0]; 26 | for (int i = 1; i < 5; i++) 27 | { 28 | if (arr[i] > tmax) 29 | tmax = arr[i]; 30 | } 31 | return tmax; 32 | } 33 | -------------------------------------------------------------------------------- /PE/ch09/9.1/golf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | void setgolf(golf & g, const char * name, int hc) 6 | { 7 | strcpy(g.fullname, name); 8 | g.handicap = hc; 9 | } 10 | 11 | int setgolf(golf & g) 12 | { 13 | using namespace std; 14 | cout << "Please enter the fullname: "; 15 | char name[Len]; 16 | cin.getline(name, Len); 17 | if (name[0] == '\0') 18 | return 0; 19 | strcpy(g.fullname, name); 20 | cout << "Please enter the handicap: "; 21 | int handicap; 22 | cin >> handicap; 23 | g.handicap = handicap; 24 | cin.get(); 25 | return 1; 26 | } 27 | 28 | void handicap(golf & g, int hc) 29 | { 30 | g.handicap = hc; 31 | } 32 | 33 | void showgolf(const golf & g) 34 | { 35 | using namespace std; 36 | cout << "Fullname: " << g.fullname << endl; 37 | cout << "handicap: " << g.handicap << endl << endl; 38 | } 39 | -------------------------------------------------------------------------------- /PE/ch09/9.1/golf.h: -------------------------------------------------------------------------------- 1 | // golf.h -- for usegolf.cpp 2 | 3 | const int Len = 40; 4 | struct golf 5 | { 6 | char fullname[Len]; 7 | int handicap; 8 | }; 9 | 10 | // non-interative version: 11 | // function sets golf structure to provided name, handicap 12 | // using values passed as arguments to the function 13 | void setgolf(golf & g, const char * name, int hc); 14 | 15 | // interactive version: 16 | // function solicits name and handicap from user 17 | // and sets the members of g to the values entered 18 | // returns 1 if name is entered, 0 if name is empty string 19 | int setgolf(golf & g); 20 | 21 | // function resets handicap to new value 22 | void handicap(golf & g, int hc); 23 | 24 | // function displays contents of golf structure 25 | void showgolf(const golf & g); 26 | -------------------------------------------------------------------------------- /PE/ch09/9.2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Redo Listing 9.9, replacing the character array with a string object. The 3 | * program should no longer have to check whether the input string fits, and 4 | * it can compare the input string to "" to check for an empty line. 5 | */ 6 | #include 7 | #include 8 | void strcount(const std::string str); 9 | 10 | int main() 11 | { 12 | using namespace std; 13 | string input; 14 | char next; 15 | 16 | cout << "Enter a line:\n"; 17 | getline(cin, input); 18 | while (input != "") 19 | { 20 | strcount(input); 21 | cout << "Enter next line (empty line to quit):\n"; 22 | getline(cin, input); 23 | } 24 | cout << "Bye!\n"; 25 | return 0; 26 | } 27 | void strcount(const std::string str) 28 | { 29 | using namespace std; 30 | static int total = 0; // static local variable 31 | 32 | cout << "\"" << str << "\" contains "; 33 | total += str.size(); 34 | cout << str.size() << " characters\n"; 35 | cout << total << " characters total\n"; 36 | } 37 | -------------------------------------------------------------------------------- /PE/ch09/9.3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Begin with the following structure declaration: 3 | * struct chaff 4 | * { 5 | * char dross[20]; 6 | * int slag; 7 | * }; 8 | * Write a program that uses placement new to place an array of two such 9 | * structures in a buffer. Then assign values to the structure members 10 | * (remembering to use strcpy() for the char array) and use a loop to 11 | * display the contents. Option 1 is to use a static array, like that in 12 | * Listing 9.10, for the buffer. Option 2 is to use regular new to allocate 13 | * the buffer. 14 | */ 15 | #include 16 | #include 17 | #include 18 | struct chaff 19 | { 20 | char dross[20]; 21 | int slag; 22 | }; 23 | chaff buffer[2]; 24 | int main() 25 | { 26 | using namespace std; 27 | chaff * item = new (buffer)chaff[2]; 28 | strcpy(item[0].dross, "coal"); 29 | item[0].slag = 20; 30 | strcpy(item[1].dross, "iron"); 31 | item[1].slag = 30; 32 | for (int i = 0; i < 2; i++) 33 | cout << item[i].dross << " " << item[i].slag << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /PE/ch09/9.4/sales.h: -------------------------------------------------------------------------------- 1 | namespace SALES 2 | { 3 | const int QUATERS = 4; 4 | struct Sales 5 | { 6 | double sales[QUATERS]; 7 | double average; 8 | double max; 9 | double min; 10 | }; 11 | // copies the lesser of 4 or n items from array ar 12 | // to the sales member of s and computes and stores the 13 | // average, maximum, and minimum values of the entered items; 14 | // remaining elements of sales, if any, set to 0 15 | void setSales(Sales & s, const double ar[], int n); 16 | // gathers sales for 4 quarters interactively, stores them 17 | // in the sales member of s and computes and stores the 18 | // average, maximum, and minimum values 19 | void setSales(Sales & s); 20 | // display all information in structure s 21 | void showSales(const Sales & s); 22 | } 23 | -------------------------------------------------------------------------------- /PE/ch09/9.4/usesales.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a three-file program based on the following namespace: 3 | * (in sales.h) 4 | * The first file should be a header file that contains the namespace. The 5 | * second file should be a source code file that extends the namespace to 6 | * provide definitions for the three prototyped functions. The third file 7 | * should declare two Sales objects. It should use the interactive version 8 | * of setSales() to provide values for one structure and the non-interactive 9 | * version of setSales() to provide values for the second structure. It 10 | * should display the contents of both structures by using showSales(). 11 | */ 12 | #include 13 | #include "sales.h" 14 | int main() 15 | { 16 | using namespace SALES; 17 | Sales sale[2]; 18 | setSales(sale[0]); 19 | double ar[4] = {34.5, 45.6, 56.7, 67.8}; 20 | setSales(sale[1], ar, 4); 21 | for (int i = 0; i < 2; i++) 22 | showSales(sale[i]); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /PE/ch10/10.1/account.h: -------------------------------------------------------------------------------- 1 | #ifndef ACCOUNT_H_ 2 | #define ACCOUNT_H_ 3 | #include 4 | class Account 5 | { 6 | private: 7 | std::string name; 8 | std::string number; 9 | double balance; 10 | public: 11 | Account(); 12 | Account(std::string m_name, std::string m_number, double m_balance); 13 | void display(); 14 | void deposit(double in); 15 | void withdraw(double out); 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch10/10.1/useaccount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "account.h" 3 | int main() 4 | { 5 | using namespace std; 6 | Account tester("Program Tester", "1234567890987654", 3000); 7 | tester.display(); 8 | tester.deposit(2000); 9 | tester.display(); 10 | tester.withdraw(4000); 11 | tester.display(); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /PE/ch10/10.2/person.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "person.h" 4 | using namespace std; 5 | Person::Person(const string & ln, const char * fn) 6 | { 7 | lname = ln; 8 | strcpy(fname, fn); 9 | } 10 | void Person::Show() const 11 | { 12 | cout << fname << " " << lname << endl; 13 | } 14 | void Person::FormalShow() const 15 | { 16 | cout << lname << ", " << fname << endl; 17 | } 18 | -------------------------------------------------------------------------------- /PE/ch10/10.2/person.h: -------------------------------------------------------------------------------- 1 | #ifndef PERSON_H_ 2 | #define PERSON_H_ 3 | #include 4 | using namespace std; 5 | class Person { 6 | private: 7 | static const int LIMIT = 25; 8 | string lname; // Person's last name 9 | char fname[LIMIT]; // Person's first name 10 | public: 11 | Person() {lname = ""; fname[0] = '\0';} // #1 12 | Person(const string & ln, const char * fn = "Heyyou"); // #2 13 | // the following methods display lname and fname 14 | void Show() const; // firstname lastname format 15 | void FormalShow() const; // lastname, firstname format 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch10/10.2/useperson.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Here is a rather simple class definition: 3 | * (in person.h) 4 | * (It uses both a string object and a character array so that you can 5 | * compare how the two forms are used.) Write a program that completes the 6 | * implementation by providing code for the undefined methods.The program 7 | * in which you use the class should also use the three possible 8 | * constructor calls (no arguments, one argument, and two arguments) and 9 | * the two display methods. Here’s an example that uses the constructors 10 | * and methods: 11 | * (And that's this file.) 12 | */ 13 | #include 14 | #include "person.h" 15 | int main() 16 | { 17 | Person one; 18 | Person two("Smythcraft"); 19 | Person three("Dimwiddy", "Sam"); 20 | one.Show(); 21 | cout << endl; 22 | one.FormalShow(); 23 | two.Show(); 24 | two.FormalShow(); 25 | three.Show(); 26 | three.FormalShow(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /PE/ch10/10.3/golf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "golf.h" 4 | 5 | Golf::Golf(const char * name, int hc) 6 | { 7 | strcpy(fullname, name); 8 | handicap = hc; 9 | } 10 | 11 | int Golf::setgolf() 12 | { 13 | using namespace std; 14 | cout << "Please enter the fullname: "; 15 | char name[Len]; 16 | cin.getline(name, Len); 17 | if (name[0] == '\0') 18 | return 0; 19 | cout << "Please enter the handicap: "; 20 | int hc; 21 | cin >> hc; 22 | *this = Golf(name, hc); 23 | cin.get(); 24 | return 1; 25 | } 26 | 27 | void Golf::sethandicap(int hc) 28 | { 29 | handicap = hc; 30 | } 31 | 32 | void Golf::showgolf() const 33 | { 34 | using namespace std; 35 | cout << "Fullname: " << fullname << endl; 36 | cout << "handicap: " << handicap << endl << endl; 37 | } 38 | -------------------------------------------------------------------------------- /PE/ch10/10.3/golf.h: -------------------------------------------------------------------------------- 1 | // golf.h -- for usegolf.cpp 2 | #ifndef GOLF_H_ 3 | #define GOLF_H_ 4 | class Golf 5 | { 6 | private: 7 | static const int Len = 40; 8 | char fullname[Len]; 9 | int handicap; 10 | public: 11 | Golf() {fullname[0]='\0', handicap=0;} 12 | Golf(const char * name, int hc); 13 | int setgolf(); // interactive version 14 | void sethandicap(int hc); 15 | void showgolf() const; 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch10/10.3/usegolf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "golf.h" 3 | int main() 4 | { 5 | using namespace std; 6 | Golf player[8]; 7 | player[0] = Golf("Ann Birdfree", 24); 8 | int count = 1; 9 | for (int i = 1; i < 8; i++) 10 | { 11 | if (!player[i].setgolf()) 12 | { 13 | cout << "Input terminated.\n"; 14 | break; 15 | } 16 | else 17 | count++; 18 | } 19 | for (int i = 0; i < count; i++) 20 | player[i].showgolf(); 21 | cout << "Now you can change Ann Birdfree's handicap: "; 22 | int hdcp; 23 | cin >> hdcp; 24 | player[0].sethandicap(hdcp); 25 | for (int i = 0; i < count; i++) 26 | player[i].showgolf(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /PE/ch10/10.4/sales.h: -------------------------------------------------------------------------------- 1 | #ifndef SALES_H_ 2 | #define SALES_H_ 3 | namespace SALES 4 | { 5 | class Sales 6 | { 7 | private: 8 | static const int QUATERS = 4; 9 | double sales[QUATERS]; 10 | double average; 11 | double max; 12 | double min; 13 | public: 14 | Sales(); 15 | Sales(const double ar[], int n); 16 | void setSales(); 17 | void showSales() const; 18 | }; 19 | } 20 | #endif 21 | -------------------------------------------------------------------------------- /PE/ch10/10.4/usesales.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Do Programming Exercise 4 from Chapter 9 but convert the Sales structure 3 | * and its associated functions to a class and its methods. Replace the 4 | * setSales(Sales &, double [], int) function with a constructor. Implement 5 | * the interactive setSales(Sales &) method by using the constructor. Keep 6 | * the class within the namespace SALES. 7 | */ 8 | #include 9 | #include "sales.h" 10 | int main() 11 | { 12 | using namespace SALES; 13 | Sales sale[2]; 14 | sale[0].setSales(); 15 | double ar[4] = {34.5, 45.6, 56.7, 67.8}; 16 | sale[1] = Sales(ar, 4); 17 | for (int i = 0; i < 2; i++) 18 | sale[i].showSales(); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /PE/ch10/10.5/stack.cpp: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | Stack::Stack() 3 | { 4 | top = 0; 5 | } 6 | 7 | bool Stack::isempty() const 8 | { 9 | return top == 0; 10 | } 11 | 12 | bool Stack::isfull() const 13 | { 14 | return top == MAX; 15 | } 16 | 17 | bool Stack::push(const Item & item) 18 | { 19 | if (top < MAX) 20 | { 21 | items[top++] = item; 22 | return true; 23 | } 24 | else 25 | return false; 26 | } 27 | 28 | bool Stack::pop(Item & item) 29 | { 30 | if (top > 0) 31 | { 32 | item = items[--top]; 33 | return true; 34 | } 35 | else 36 | return false; 37 | } 38 | -------------------------------------------------------------------------------- /PE/ch10/10.5/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H_ 2 | #define STACK_H_ 3 | struct customer { 4 | char fullname[35]; 5 | double payment; 6 | }; 7 | typedef customer Item; 8 | 9 | class Stack 10 | { 11 | private: 12 | enum {MAX = 10}; 13 | Item items[MAX]; 14 | int top; 15 | public: 16 | Stack(); 17 | bool isempty() const; 18 | bool isfull() const; 19 | bool push(const Item & item); 20 | bool pop(Item & item); 21 | }; 22 | #endif 23 | -------------------------------------------------------------------------------- /PE/ch10/10.6/move.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "move.h" 3 | Move::Move(double a, double b) 4 | { 5 | x = a; 6 | y = b; 7 | } 8 | 9 | void Move::showmove() const 10 | { 11 | std::cout << "(" << x << ", " << y << ")\n"; 12 | } 13 | 14 | Move Move::add(const Move & m) const 15 | { 16 | double tmp_x, tmp_y; 17 | tmp_x = m.x + x; 18 | tmp_y = m.y + y; 19 | return Move(tmp_x, tmp_y); 20 | } 21 | 22 | void Move::reset(double a, double b) 23 | { 24 | x = a; 25 | y = b; 26 | } 27 | -------------------------------------------------------------------------------- /PE/ch10/10.6/move.h: -------------------------------------------------------------------------------- 1 | #ifndef MOVE_H_ 2 | #define MOVE_H_ 3 | class Move 4 | { 5 | private: 6 | double x; 7 | double y; 8 | public: 9 | Move(double a = 0, double b = 0); // sets x, y to a, b 10 | void showmove() const; // shows current x, y values 11 | Move add(const Move & m) const; 12 | // this function adds x of m to x of invoking object to get new x, 13 | // adds y of m to y of invoking object to get new y, creates a new 14 | // move object initialized to new x, y values and returns it 15 | void reset(double a = 0, double b = 0); // resets x,y to a, b 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch10/10.6/usemove.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Here's a class definition: 3 | * (In move.h) 4 | * Create member function definitions and a program that exercises the 5 | * class. 6 | */ 7 | #include 8 | #include "move.h" 9 | int main() 10 | { 11 | using namespace std; 12 | Move m1; 13 | Move m2(3,4); 14 | cout << "m1: "; 15 | m1.showmove(); 16 | cout << "m2: "; 17 | m2.showmove(); 18 | m1.reset(1,2); 19 | cout << "m1: "; 20 | m1.showmove(); 21 | Move m3 = m1.add(m2); 22 | cout << "m3: "; 23 | m3.showmove(); 24 | m3.reset(); 25 | cout << "Now m3: "; 26 | m3.showmove(); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /PE/ch10/10.7/plorg.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "plorg.h" 4 | Plorg::Plorg(const char * star_name) 5 | { 6 | strcpy(name, star_name); 7 | ci = 50; 8 | } 9 | 10 | void Plorg::setCI(int star_ci) 11 | { 12 | ci = star_ci; 13 | } 14 | 15 | void Plorg::report() const 16 | { 17 | std::cout << "Name: " << name << " " << "CI: " << ci << std::endl; 18 | } 19 | -------------------------------------------------------------------------------- /PE/ch10/10.7/plorg.h: -------------------------------------------------------------------------------- 1 | #ifndef PLORG_H_ 2 | #define PLORG_H_ 3 | class Plorg 4 | { 5 | private: 6 | char name[20]; 7 | int ci; 8 | public: 9 | Plorg(const char * star_name="Plorga"); 10 | void setCI(int star_ci); 11 | void report() const; 12 | }; 13 | #endif 14 | -------------------------------------------------------------------------------- /PE/ch10/10.7/useplorg.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * A Betelgeusean plorg has three properties: 3 | * Data: 4 | * A plorg has a name with no more than 19 letters. 5 | * A plorg has a contentment index (CI), which is an integer. 6 | * Operations 7 | * A new plorg starts out with a name and a CI of 50. 8 | * A plorg's CI can change. 9 | * A plorg can report its name and CI. 10 | * The default plorg has the name "Plorga". 11 | * Write a Plorg class declaration (including data members and member 12 | * function prototypes) that represents a plorg. Write the function 13 | * definitions for the member functions. Write a short program that 14 | * demonstrates all the features of the Plorg class. 15 | */ 16 | #include 17 | #include "plorg.h" 18 | int main() 19 | { 20 | Plorg p1; 21 | Plorg p2("Orion"); 22 | p1.report(); 23 | p2.report(); 24 | std::cout << "Change the CI of Orion: "; 25 | int orion_ci; 26 | std::cin >> orion_ci; 27 | p2.setCI(orion_ci); 28 | p2.report(); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch10/10.8/Array/list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "list.h" 3 | List::List() 4 | { 5 | count = 0; 6 | } 7 | bool List::add(Item data) 8 | { 9 | if (this->isFull()) 10 | { 11 | std::cout << "The list is full.\n"; 12 | return false; 13 | } 14 | else 15 | { 16 | items[count++] = data; 17 | return true; 18 | } 19 | } 20 | bool List::isEmpty() 21 | { 22 | return count == 0; 23 | } 24 | bool List::isFull() 25 | { 26 | return count == MAX; 27 | } 28 | void List::visit(void (*pf)(Item &)) 29 | { 30 | if (this->isEmpty()) 31 | std::cout << "The list is empty.\n"; 32 | else 33 | for (int i = 0; i < count; i++) 34 | pf(items[i]); 35 | } 36 | -------------------------------------------------------------------------------- /PE/ch10/10.8/Array/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H_ 2 | #define LIST_H_ 3 | typedef double Item; 4 | class List 5 | { 6 | private: 7 | static const int MAX = 10; 8 | Item items[MAX]; 9 | int count; 10 | public: 11 | List(); 12 | bool add(Item data); 13 | bool isEmpty(); 14 | bool isFull(); 15 | void visit(void (*pf)(Item &)); 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch10/10.8/Array/uselist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "list.h" 3 | using namespace std; 4 | void display(Item &); 5 | void triple(Item &); 6 | int main() 7 | { 8 | List numbers; 9 | cout << "Enter at most 10 numbers, q to quit:\n"; 10 | double num; 11 | while (cin >> num && !numbers.isFull()) 12 | numbers.add(num); 13 | cout << "Your input: " << endl; 14 | numbers.visit(display); 15 | numbers.visit(triple); 16 | cout << "After triple: " << endl; 17 | numbers.visit(display); 18 | return 0; 19 | } 20 | void display(Item & data) 21 | { 22 | cout << data << endl; 23 | } 24 | void triple(Item & data) 25 | { 26 | data *= 3; 27 | } 28 | -------------------------------------------------------------------------------- /PE/ch10/10.8/LinkedList/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H_ 2 | #define LIST_H_ 3 | typedef double Item; 4 | struct Node 5 | { 6 | Item data; 7 | Node * next; 8 | }; 9 | class List 10 | { 11 | private: 12 | static const int MAX = 10; 13 | Node * head; 14 | int count; 15 | public: 16 | List(); 17 | ~List(); 18 | bool add(Item data); 19 | bool isEmpty(); 20 | bool isFull(); 21 | void visit(void (*pf)(Item &)); 22 | }; 23 | #endif 24 | -------------------------------------------------------------------------------- /PE/ch10/10.8/LinkedList/uselist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "list.h" 3 | using namespace std; 4 | void display(Item &); 5 | void triple(Item &); 6 | int main() 7 | { 8 | List numbers; 9 | cout << "Enter at most 10 numbers, q to quit:\n"; 10 | double num; 11 | while (cin >> num && !numbers.isFull()) 12 | numbers.add(num); 13 | cout << "Your input: " << endl; 14 | numbers.visit(display); 15 | numbers.visit(triple); 16 | cout << "After triple: " << endl; 17 | numbers.visit(display); 18 | return 0; 19 | } 20 | void display(Item & data) 21 | { 22 | cout << data << endl; 23 | } 24 | void triple(Item & data) 25 | { 26 | data *= 3; 27 | } 28 | -------------------------------------------------------------------------------- /PE/ch11/11.4/mytime.h: -------------------------------------------------------------------------------- 1 | #ifndef MYTIME_H_ 2 | #define MYTIME_H_ 3 | #include 4 | 5 | class Time 6 | { 7 | private: 8 | int hours; 9 | int minutes; 10 | public: 11 | Time(); 12 | Time(int h, int m = 0); 13 | void AddMin(int m); 14 | void AddHr(int h); 15 | void Reset(int h = 0, int m = 0); 16 | friend Time operator+(const Time & t1, const Time & t2); 17 | friend Time operator-(const Time & t1, const Time & t2); 18 | friend Time operator*(const Time & t, double n); 19 | friend Time operator*(double m, const Time & t) {return t*m;}; 20 | friend std::ostream & operator<<(std::ostream & os, const Time & t); 21 | }; 22 | #endif 23 | -------------------------------------------------------------------------------- /PE/ch11/11.4/usetime.cpp: -------------------------------------------------------------------------------- 1 | // usetime3.cpp -- using the fourth draft of the Time class 2 | // complile usetime3.cpp and mytime3.cpp together 3 | #include 4 | #include "mytime.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | Time aida(3, 35); 11 | Time tosca(2, 48); 12 | Time temp; 13 | 14 | cout << "Aida and Tosca:\n"; 15 | cout << aida << "; " << tosca << endl; 16 | temp = aida + tosca; // operator+() 17 | cout << "Aida + Tosca: " << temp << endl; 18 | temp = aida * 1.17; // member operator*() 19 | cout << "Aida * 1.17: " << temp << endl; 20 | cout << "10.0 * Tosca: " << 10.0 * tosca << endl; 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /PE/ch11/11.6/stonewt.h: -------------------------------------------------------------------------------- 1 | #ifndef STONEWT_H_ 2 | #define STONEWT_H_ 3 | class Stonewt 4 | { 5 | private: 6 | enum {Lbs_per_stn = 14}; // pounds per stone 7 | int stone; // whole stones 8 | double pds_left; // fractional pounds 9 | double pounds; // entire weight in pounds 10 | public: 11 | Stonewt(double lbs); // constructor for double pounds 12 | Stonewt(int stn, double lbs); // constructor for stone, lbs 13 | Stonewt(); // default constructor 14 | ~Stonewt(); 15 | void show_lbs() const; 16 | void show_stn() const; 17 | bool operator<(const Stonewt & s) const; 18 | bool operator<=(const Stonewt & s) const; 19 | bool operator==(const Stonewt & s) const; 20 | bool operator>=(const Stonewt & s) const; 21 | bool operator>(const Stonewt & s) const; 22 | bool operator!=(const Stonewt & s) const; 23 | }; 24 | #endif 25 | -------------------------------------------------------------------------------- /PE/ch11/11.7/complex0.h: -------------------------------------------------------------------------------- 1 | #ifndef COMPLEX0_H_ 2 | #define COMPLEX0_H_ 3 | #include 4 | class complex 5 | { 6 | private: 7 | double real; 8 | double imag; 9 | public: 10 | complex(); 11 | complex(double r, double i=0.0); 12 | complex operator+(const complex & c) const; 13 | complex operator-(const complex & c) const; 14 | complex operator*(double x) const; 15 | complex operator*(const complex & c) const; 16 | complex operator~() const; 17 | friend complex operator*(double x, const complex & c){return c*x;}; 18 | friend std::istream & operator>>(std::istream & is, complex & c); 19 | friend std::ostream & operator<<(std::ostream & os, const complex & c); 20 | }; 21 | #endif 22 | -------------------------------------------------------------------------------- /PE/ch12/12.1/cow.h: -------------------------------------------------------------------------------- 1 | #ifndef COW_H_ 2 | #define COW_H_ 3 | class Cow 4 | { 5 | private: 6 | char name[20]; 7 | char * hobby; 8 | double weight; 9 | public: 10 | Cow(); 11 | Cow(const char * nm, const char * ho, double wt); 12 | Cow(const Cow & c); 13 | ~Cow(); 14 | Cow & operator=(const Cow & c); 15 | void ShowCow() const; // display all cow data 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch12/12.1/usecow.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Consider the following class declaration 3 | * (in cow.h) 4 | * Provide the implementation for this class and write a short program that 5 | * uses all the member functions. 6 | */ 7 | #include 8 | #include "cow.h" 9 | int main() 10 | { 11 | Cow c1; 12 | Cow c2("Moo", "Eating grass", 120); 13 | Cow c3("Bull", "Fighting", 140); 14 | c1 = c2; 15 | c1.ShowCow(); 16 | c2.ShowCow(); 17 | Cow c4(c3); 18 | c3.ShowCow(); 19 | c4.ShowCow(); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /PE/ch12/12.2/question.txt: -------------------------------------------------------------------------------- 1 | Enhance the String class declaration (that is, upgrade string1.h to string2.h ) by doing the following: 2 | a. Overload the + operator to allow you to join two strings into one. 3 | b. Provide a stringlow() member function that converts all alphabetic characters in a string to lowercase. (Don’t forget the cctype family of character functions.) 4 | c. Provide a stringup() member function that converts all alphabetic characters in a string to uppercase. 5 | d. Provide a member function that takes a char argument and returns the number of times the character appears in the string. 6 | Test your work in the following program: 7 | (It's pe12_2.cpp) 8 | Your output should look like this sample run: 9 | Please enter your name: Fretta Farbo 10 | My name is Fretta Farbo. 11 | The string 12 | MY NAME IS FRETTA FARBO AND I AM A C++ STUDENT. 13 | contains 6 'A' characters in it. 14 | Enter the name of a primary color for mixing light: yellow 15 | Try again! 16 | BLUE 17 | That's right! 18 | Bye 19 | -------------------------------------------------------------------------------- /PE/ch12/12.3/stock.h: -------------------------------------------------------------------------------- 1 | #ifndef STOCK_H_ 2 | #define STOCK_H_ 3 | #include 4 | class Stock 5 | { 6 | private: 7 | char * company; 8 | int shares; 9 | double share_val; 10 | double total_val; 11 | void set_tot() { total_val = shares * share_val; } 12 | public: 13 | Stock(); 14 | Stock(const char * co, long n = 0, double pr = 0.0); 15 | Stock(const Stock & st); 16 | ~Stock(); 17 | Stock & operator=(const Stock & st); 18 | void buy(long num, double price); 19 | void sell(long num, double price); 20 | void update(double price); 21 | const Stock & topval(const Stock & s) const; 22 | friend std::ostream & operator<<(std::ostream & os, const Stock & st); 23 | }; 24 | #endif 25 | -------------------------------------------------------------------------------- /PE/ch12/12.3/usestock.cpp: -------------------------------------------------------------------------------- 1 | // usestock.cpp -- using the Stock class 2 | // compile with stock.cpp 3 | #include 4 | #include "stock.h" 5 | 6 | const int STKS = 4; 7 | int main() 8 | { 9 | // create an array of initialized objects 10 | Stock stocks[STKS] = { 11 | Stock("NanoSmart", 12, 20.0), 12 | Stock("Boffo Objects", 200, 2.0), 13 | Stock("Monolithic Obelisks", 130, 3.25), 14 | Stock("Fleep Enterprises", 60, 6.5) 15 | }; 16 | 17 | std::cout << "Stock holdings:\n"; 18 | int st; 19 | for (st = 0; st < STKS; st++) 20 | std::cout << stocks[st]; 21 | // set pointer to first element 22 | const Stock * top = &stocks[0]; 23 | for (st = 1; st < STKS; st++) 24 | top = &top->topval(stocks[st]); 25 | // now top points to the most valuable holding 26 | std::cout << "\nMost valuable holding:\n"; 27 | std::cout << *top; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /PE/ch12/12.4/stack.h: -------------------------------------------------------------------------------- 1 | // stack.h -- class declaration for the stack ADT 2 | #ifndef STACK_H_ 3 | #define STACK_H_ 4 | 5 | typedef unsigned long Item; 6 | 7 | class Stack 8 | { 9 | private: 10 | enum {MAX = 10}; // constant specific to class 11 | Item * pitems; // holds stack items 12 | int size; // number of elements in stack 13 | int top; // index for top stack item 14 | public: 15 | Stack(int n = MAX); // creates stack with n elements 16 | Stack(const Stack & st); 17 | ~Stack(); 18 | bool isempty() const; 19 | bool isfull() const; 20 | // push() returns false if stack already is full, true otherwise 21 | bool push(const Item & item); // add item to stack 22 | // pop() returns false if stack already is empty, true otherwise 23 | bool pop(Item & item); // pop top into item 24 | Stack & operator=(const Stack & st); 25 | }; 26 | #endif 27 | -------------------------------------------------------------------------------- /PE/ch13/13.1/cd.h: -------------------------------------------------------------------------------- 1 | #ifndef CD_H_ 2 | #define CD_H_ 3 | // base class 4 | class Cd // represents a CD disk 5 | { 6 | private: 7 | char performers[50]; 8 | char label[20]; 9 | int selections; // number of selections 10 | double playtime; // playing time in minutes 11 | public: 12 | Cd(const char * s1, const char * s2, int n, double x); 13 | Cd(const Cd & d); 14 | Cd(); 15 | virtual ~Cd() {}; 16 | virtual void Report() const; // reports all CD data 17 | Cd & operator=(const Cd & d); 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /PE/ch13/13.1/classic.h: -------------------------------------------------------------------------------- 1 | #ifndef CLASSIC_H_ 2 | #define CLASSIC_H_ 3 | #include "cd.h" 4 | class Classic : public Cd 5 | { 6 | private: 7 | char primary[50]; 8 | public: 9 | Classic(const char * pri, const char * per, const char * l, 10 | int n, double x); 11 | Classic(const Cd & d, const char * pri); 12 | Classic(const Classic & c); 13 | Classic(); 14 | virtual void Report() const; 15 | Classic & operator=(const Classic & d); 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /PE/ch13/13.1/question.txt: -------------------------------------------------------------------------------- 1 | Start with the following class declaration: 2 | // base class 3 | class Cd { // represents a CD disk 4 | private: 5 | char performers[50]; 6 | char label[20]; 7 | int selections; // number of selections 8 | double playtime; // playing time in minutes 9 | public: 10 | Cd(char * s1, char * s2, int n, double x); 11 | Cd(const Cd & d); 12 | Cd(); 13 | ~Cd(); 14 | void Report() const; // reports all CD data 15 | Cd & operator=(const Cd & d); 16 | }; 17 | 18 | Derive a Classic class that adds an array of char members that will hold a string identifying the primary work on the CD. If the base class requires that any functions be virtual, modify the base-class declaration to make it so. If a declared method is not needed, remove it from the definition.Test your product with the following program: 19 | (It's useclassic.cpp) 20 | -------------------------------------------------------------------------------- /PE/ch13/13.1/useclassic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include "classic.h" // which will contain #include cd.h 4 | void Bravo(const Cd & disk); 5 | int main() 6 | { 7 | Cd c1("Beatles", "Capitol", 14, 35.5); 8 | Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", 9 | "Alfred Brendel", "Philips", 2, 57.17); 10 | Cd *pcd = &c1; 11 | 12 | cout << "Using object directly:\n"; 13 | c1.Report(); // use Cd method 14 | c2.Report(); // use Classic method 15 | 16 | cout << "Using type cd * pointer to objects:\n"; 17 | pcd->Report(); // use Cd method for cd object 18 | pcd = &c2; 19 | pcd->Report(); // use Classic method for classic object 20 | cout << "Calling a function with a Cd reference argument:\n"; 21 | Bravo(c1); 22 | Bravo(c2); 23 | 24 | cout << "Testing assignment: "; 25 | Classic copy; 26 | copy = c2; 27 | copy.Report(); 28 | 29 | return 0; 30 | } 31 | 32 | void Bravo(const Cd & disk) 33 | { 34 | disk.Report(); 35 | } 36 | -------------------------------------------------------------------------------- /PE/ch13/13.2/cd.h: -------------------------------------------------------------------------------- 1 | #ifndef CD_H_ 2 | #define CD_H_ 3 | // base class 4 | class Cd // represents a CD disk 5 | { 6 | private: 7 | char * performers; 8 | char * label; 9 | int selections; // number of selections 10 | double playtime; // playing time in minutes 11 | public: 12 | Cd(const char * s1, const char * s2, int n, double x); 13 | Cd(const Cd & d); 14 | Cd(); 15 | virtual ~Cd(); 16 | virtual void Report() const; // reports all CD data 17 | Cd & operator=(const Cd & d); 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /PE/ch13/13.2/classic.h: -------------------------------------------------------------------------------- 1 | #ifndef CLASSIC_H_ 2 | #define CLASSIC_H_ 3 | #include "cd.h" 4 | class Classic : public Cd 5 | { 6 | private: 7 | char * primary; 8 | public: 9 | Classic(const char * pri, const char * per, const char * l, 10 | int n, double x); 11 | Classic(const Cd & d, const char * pri); 12 | Classic(const Classic & c); 13 | Classic(); 14 | virtual ~Classic(); 15 | virtual void Report() const; 16 | Classic & operator=(const Classic & d); 17 | }; 18 | #endif 19 | -------------------------------------------------------------------------------- /PE/ch13/13.4/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "port.h" 3 | using namespace std; 4 | int main() 5 | { 6 | Port gallo("Gallo", "tawny", 20); 7 | gallo.Show(); 8 | gallo += 30; 9 | gallo.Show(); 10 | gallo -= 5; 11 | gallo.Show(); 12 | cout << gallo << endl; 13 | Port foo; 14 | foo = gallo; 15 | foo.Show(); 16 | 17 | VintagePort lafi("Lafite", 45, "The Noble", 1982); 18 | lafi.Show(); 19 | lafi -= 10; 20 | lafi.Show(); 21 | lafi += 5; 22 | lafi.Show(); 23 | cout << lafi << endl; 24 | VintagePort bar; 25 | bar = lafi; 26 | bar.Show(); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /PE/ch14/14.1/pair.h: -------------------------------------------------------------------------------- 1 | #ifndef PAIR_H_ 2 | #define PAIR_H_ 3 | template 4 | class Pair 5 | { 6 | private: 7 | T1 a; 8 | T2 b; 9 | public: 10 | T1 & first(); 11 | T2 & second(); 12 | T1 first() const { return a; } 13 | T2 second() const { return b; } 14 | Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval) { } 15 | Pair() {} 16 | }; 17 | 18 | template 19 | T1 & Pair::first() 20 | { 21 | return a; 22 | } 23 | template 24 | T2 & Pair::second() 25 | { 26 | return b; 27 | } 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /PE/ch14/14.1/usewinec.cpp: -------------------------------------------------------------------------------- 1 | // pe14-1.cpp -- using Wine class with containment 2 | #include 3 | #include"winec.h" 4 | 5 | int main ( void ) 6 | { 7 | using std::cin; 8 | using std::cout; 9 | using std::endl; 10 | 11 | cout << "Enter name of wine: "; 12 | char lab[50]; 13 | cin.getline(lab, 50); 14 | cout << "Enter number of years: "; 15 | int yrs; 16 | cin >> yrs; 17 | 18 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 19 | holding.GetBottles(); // solicit input for year, bottle count 20 | holding.Show(); // display object contents 21 | 22 | const int YRS = 3; 23 | int y[YRS] = {1993, 1995, 1998}; 24 | int b[YRS] = { 48, 60, 72}; 25 | // create new object, initialize using data in arrays y and b 26 | Wine more("Gushing Grape Red", YRS, y, b); 27 | more.Show(); 28 | cout << "Total bottles for " << more.Label() // use Label() method 29 | << ": " << more.sum() << endl; // use sum() method 30 | cout << "Bye\n"; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /PE/ch14/14.1/winec.h: -------------------------------------------------------------------------------- 1 | #ifndef WINEC_H_ 2 | #define WINEC_H_ 3 | 4 | #include 5 | #include 6 | #include "pair.h" 7 | 8 | class Wine 9 | { 10 | private: 11 | typedef std::valarray ArrayInt; 12 | typedef Pair PairArray; 13 | std::string label; // wine brandname 14 | int years; // number of years 15 | PairArray data; 16 | 17 | public: 18 | Wine() : label("none"), years(0), data(ArrayInt(),ArrayInt()) {} 19 | Wine(const char * l, int y, const int yr[], const int bot[]); 20 | Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot); 21 | Wine(const char * l, const PairArray & yr_bot); 22 | Wine(const char * l, int y); 23 | void GetBottles(); 24 | void Show() const; 25 | const std::string & Label() { return label; } 26 | int sum() const { return data.second().sum(); } 27 | }; 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /PE/ch14/14.2/pair.h: -------------------------------------------------------------------------------- 1 | #ifndef PAIR_H_ 2 | #define PAIR_H_ 3 | template 4 | class Pair 5 | { 6 | private: 7 | T1 a; 8 | T2 b; 9 | public: 10 | T1 & first(); 11 | T2 & second(); 12 | T1 first() const { return a; } 13 | T2 second() const { return b; } 14 | Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval) { } 15 | Pair() {} 16 | }; 17 | 18 | template 19 | T1 & Pair::first() 20 | { 21 | return a; 22 | } 23 | template 24 | T2 & Pair::second() 25 | { 26 | return b; 27 | } 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /PE/ch14/14.2/usewinei.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "winei.h" 3 | 4 | int main ( void ) 5 | { 6 | using std::cin; 7 | using std::cout; 8 | using std::endl; 9 | 10 | cout << "Enter name of wine: "; 11 | char lab[50]; 12 | cin.getline(lab, 50); 13 | cout << "Enter number of years: "; 14 | int yrs; 15 | cin >> yrs; 16 | 17 | Wine holding(lab, yrs); // store label, years, give arrays yrs elements 18 | holding.GetBottles(); // solicit input for year, bottle count 19 | holding.Show(); // display object contents 20 | 21 | const int YRS = 3; 22 | int y[YRS] = {1993, 1995, 1998}; 23 | int b[YRS] = { 48, 60, 72}; 24 | // create new object, initialize using data in arrays y and b 25 | Wine more("Gushing Grape Red", YRS, y, b); 26 | more.Show(); 27 | cout << "Total bottles for " << more.Label() // use Label() method 28 | << ": " << more.sum() << endl; // use sum() method 29 | cout << "Bye\n"; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /PE/ch14/14.2/winei.h: -------------------------------------------------------------------------------- 1 | #ifndef WINEI_H_ 2 | #define WINEI_H_ 3 | #include 4 | #include 5 | #include "pair.h" 6 | 7 | class Wine : private std::string, 8 | private Pair, std::valarray > 9 | { 10 | private: 11 | typedef std::valarray ArrayInt; 12 | typedef Pair PairArray; 13 | int years; // number of years 14 | public: 15 | Wine() : std::string("none"), years(0), PairArray(ArrayInt(), 16 | ArrayInt()) { } 17 | Wine(const char * l, int y, const int yr[], const int bot[]); 18 | Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot); 19 | Wine(const char * l, const PairArray & yr_bot); 20 | Wine(const char * l, int y); 21 | void GetBottles(); 22 | void Show() const; 23 | const std::string & Label() const; 24 | int sum() const; 25 | }; 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /PE/ch14/14.5/useemp1.cpp: -------------------------------------------------------------------------------- 1 | // pe14-5.cpp 2 | // useemp1.cpp -- using the abstr_emp classes 3 | 4 | #include 5 | using namespace std; 6 | #include "emp.h" 7 | 8 | int main(void) 9 | { 10 | employee em("Trip", "Harris", "Thumper"); 11 | cout << em << endl; 12 | em.ShowAll(); 13 | manager ma("Amorphia", "Spindragon", "Nuancer", 5); 14 | cout << ma << endl; 15 | ma.ShowAll(); 16 | 17 | 18 | fink fi("Matt", "Oggs", "Oiler", "Juno Barr"); 19 | cout << fi << endl; 20 | fi.ShowAll(); 21 | highfink hf(ma, "Curly Kew"); // recruitment? 22 | hf.ShowAll(); 23 | cout << "Press a key for next phase:\n"; 24 | cin.get(); 25 | highfink hf2; 26 | hf2.SetAll(); 27 | 28 | cout << "Using an abstr_emp * pointer:\n"; 29 | abstr_emp * tri[4] = {&em, &fi, &hf, &hf2}; 30 | for (int i = 0; i < 4; i++) 31 | tri[i]->ShowAll(); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /PE/ch15/15.2/exc_mean.h: -------------------------------------------------------------------------------- 1 | #include 2 | // exception class 3 | class bad_hmean : public std::logic_error 4 | { 5 | public: 6 | bad_hmean() : 7 | std::logic_error("hmean(): invalid arguments: a = -b\n") 8 | { 9 | } 10 | }; 11 | class bad_gmean : public std::logic_error 12 | { 13 | public: 14 | bad_gmean() : 15 | std::logic_error("gmean(): arguments should be >= 0\n") 16 | { 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /PE/ch15/15.3/exc_mean.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "exc_mean.h" 3 | 4 | using std::cout; 5 | 6 | bad_mean::bad_mean(double a, double b, const std::string & s) 7 | : std::logic_error(s), v1(a), v2(b) 8 | { 9 | } 10 | 11 | bad_hmean::bad_hmean(double a, double b) 12 | : bad_mean(a, b, "hmean(): invalid arguments") 13 | { 14 | } 15 | 16 | void bad_hmean::report_bad() 17 | { 18 | cout << "hmean(" << bad_mean::v1_val() << "," << bad_mean::v2_val() 19 | << "): invalid arguments: a = -b\n"; 20 | } 21 | 22 | bad_gmean::bad_gmean(double a, double b) 23 | : bad_mean(a,b, "gmean(): invalid arguments") 24 | { 25 | } 26 | 27 | void bad_gmean::report_bad() 28 | { 29 | cout << "gmean(" << bad_mean::v1_val() << "," << bad_mean::v2_val() 30 | << "): invalid arguments: arguments should be >= 0\n"; 31 | } 32 | -------------------------------------------------------------------------------- /PE/ch15/15.3/exc_mean.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // base class 4 | class bad_mean : public std::logic_error 5 | { 6 | private: 7 | double v1; 8 | double v2; 9 | public: 10 | bad_mean(double a, double b, 11 | const std::string & s = "Invalid arguments\n"); 12 | double v1_val() const { return v1; } 13 | double v2_val() const { return v2; } 14 | virtual void report_bad() = 0; 15 | virtual ~bad_mean() throw() { } 16 | }; 17 | 18 | class bad_hmean : public bad_mean 19 | { 20 | public: 21 | bad_hmean(double a, double b); 22 | virtual void report_bad(); 23 | virtual ~bad_hmean() throw(){} 24 | }; 25 | 26 | class bad_gmean : public bad_mean 27 | { 28 | public: 29 | bad_gmean(double a, double b); 30 | virtual void report_bad(); 31 | virtual ~bad_gmean() throw(){} 32 | }; 33 | -------------------------------------------------------------------------------- /PE/ch16/wordlist.txt: -------------------------------------------------------------------------------- 1 | apiary beetle cereal danger ensign florid garage 2 | health insult jackal keeper loaner manage nonce 3 | onset plaid quilt remote stolid train 4 | useful valid whence xenon yearn zippy 5 | -------------------------------------------------------------------------------- /PE/ch17/17.1.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that counts the number of characters up to the first $ in 2 | // input and that leaves the $ in the input stream. 3 | #include 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | char ch; 9 | int count = 0; 10 | while (cin.get(ch) && ch != '$') 11 | count++; 12 | if (ch == '$') 13 | cin.putback(ch); 14 | else 15 | cout << "End of input was reached\n"; 16 | cout << count << " characters before the first $.\n"; 17 | cin.get(ch); 18 | cout << "Then next input character is " << ch << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /PE/ch17/17.2.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that copies your keyboard input (up to the simulated 2 | // end-of-file) to a file named on the command line. 3 | #include 4 | #include 5 | #include // for exit() 6 | int main(int argc, char * argv[]) 7 | { 8 | using namespace std; 9 | if (argc != 2) 10 | { 11 | cerr << "Usage: " << argv[0] << " filename\n"; 12 | exit(EXIT_FAILURE); 13 | } 14 | 15 | ofstream fout; 16 | char ch; 17 | fout.open(argv[1]); 18 | if (!fout.is_open()) 19 | { 20 | cerr << "Could not open " << argv[1] << endl; 21 | exit(EXIT_FAILURE); 22 | } 23 | 24 | cout << "Please type characters. Ctrl-D (Unix) or Ctrl-Z(DOS) " 25 | << "to terminate.\n"; 26 | while (cin.get(ch)) 27 | fout.put(ch); 28 | 29 | fout.close(); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /PE/ch17/17.3.cpp: -------------------------------------------------------------------------------- 1 | // Write a program that copies one file to another. Have the program take 2 | // the filenames from command line. Have the program report if it cannot 3 | // open a file. 4 | #include 5 | #include 6 | #include 7 | int main(int argc, char * argv[]) 8 | { 9 | using namespace std; 10 | if (argc != 3) 11 | { 12 | cerr << "Usage: " << argv[0] << " source-file target-file\n"; 13 | exit(EXIT_FAILURE); 14 | } 15 | ifstream fin(argv[1]); 16 | if (!fin) 17 | { 18 | cerr << "Cannot open " << argv[1] << " file to read.\n"; 19 | exit(EXIT_FAILURE); 20 | } 21 | ofstream fout(argv[2]); 22 | if (!fout) 23 | { 24 | cerr << "Cannot open " << argv[2] << " file to write.\n"; 25 | exit(EXIT_FAILURE); 26 | } 27 | char ch; 28 | while (fin.get(ch)) 29 | fout << ch; 30 | cout << "Contents of " << argv[1] << " have already been copied to " 31 | << argv[2] << ".\n"; 32 | fin.close(); 33 | fout.close(); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /PE/ch18/18.1.cpp: -------------------------------------------------------------------------------- 1 | // Here is part of a short program: 2 | // (It's main() function) 3 | // Complete the program by supplying the average_list() function. It should 4 | // be a template function, with type parameter being used to specified the 5 | // kind of initialized_list template to be used as the function parameter 6 | // and also to give the function return type. 7 | #include 8 | #include 9 | template 10 | T average_list(const std::initializer_list & il) 11 | { 12 | T tot = 0; 13 | for (auto i = il.begin(); i != il.end(); i++) 14 | tot += *i; 15 | return tot / il.size(); 16 | } 17 | 18 | int main() 19 | { 20 | using namespace std; 21 | // list of double deduce from list contents 22 | auto q = average_list({15.4, 10.7, 9.0}); 23 | cout << q << endl; 24 | // list of int deduced from list contents 25 | cout << average_list({20, 30, 19, 17, 45, 38}) << endl; 26 | // forced list of double 27 | auto ad = average_list({'A', 70, 65.33}); 28 | cout << ad << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /PE/ch18/18.3.cpp: -------------------------------------------------------------------------------- 1 | // Write and test a variadic template function sum_values() that accepts an 2 | // arbitrarily long list of arguments with numeric values (they can be a 3 | // mixture of types) and return the sum as a long double value. 4 | #include 5 | 6 | long double sum_values() {return 0;} 7 | 8 | template 9 | long double sum_values(const T value) {return value;} 10 | 11 | template 12 | long double sum_values(const T value, const Args&... args) 13 | { 14 | return (value + sum_values(args...)); 15 | } 16 | 17 | int main() 18 | { 19 | using std::cout; 20 | using std::endl; 21 | cout << sum_values(1, 2, 3, 4) << endl; 22 | cout << sum_values(1.1, 2.2, 3, 4.8, 5.2) << endl; 23 | cout << sum_values(70000L, 3.56, 'c', 58, -843.66) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /ch02/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all 2 | all: myfirst carrot getinfo sqrt ourfunc convert 3 | myfirst: myfirst.o 4 | g++ -o myfirst myfirst.o 5 | carrot: carrot.o 6 | g++ -o carrot carrot.o 7 | getinfo: getinfo.o 8 | g++ -o getinfo getinfo.o 9 | sqrt: sqrt.o 10 | g++ -o sqrt sqrt.o 11 | ourfunc: ourfunc.o 12 | g++ -o ourfunc ourfunc.o 13 | convert: convert.o 14 | g++ -o convert convert.o 15 | 16 | myfirst.o: myfirst.cpp 17 | g++ -c myfirst.cpp 18 | carrot.o: carrot.cpp 19 | g++ -c carrot.cpp 20 | getinfo.o: getinfo.cpp 21 | g++ -c getinfo.cpp 22 | sqrt.o: sqrt.cpp 23 | g++ -c sqrt.cpp 24 | ourfunc.o: ourfunc.cpp 25 | g++ -c ourfunc.cpp 26 | convert.o: convert.cpp 27 | g++ -c convert.cpp 28 | 29 | .PHONY: cleanobj 30 | cleanobj: 31 | rm -f *.o 32 | 33 | .PHONY: clean 34 | clean: 35 | find . -maxdepth 1 -type f -perm /111 -exec rm {} \; 36 | rm -f *.o 37 | -------------------------------------------------------------------------------- /ch02/carrot.cpp: -------------------------------------------------------------------------------- 1 | // carrots.cpp -- food processing program 2 | // uses and displays a variable 3 | 4 | #include 5 | 6 | int main() 7 | { 8 | using namespace std; 9 | 10 | int carrots; // declare an integer variable 11 | 12 | carrots = 25; // assign a value to the variable 13 | cout << "I have "; 14 | cout << carrots; // display a value to the variable 15 | cout << " carrots."; 16 | cout << endl; 17 | carrots = carrots - 1; // modify the variable 18 | cout << "Crunch, crunch. Now I have " << carrots << " carrots." << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ch02/convert.cpp: -------------------------------------------------------------------------------- 1 | // convert.cpp -- converts stone to pounds 2 | #include 3 | int stonetolb(int); // function prototype 4 | int main() 5 | { 6 | using namespace std; 7 | int stone; 8 | cout << "Enter the weight in stone: "; 9 | cin >> stone; 10 | int pounds = stonetolb(stone); 11 | cout << stone << " stone = "; 12 | cout << pounds << " pounds." << endl; 13 | return 0; 14 | } 15 | 16 | int stonetolb(int sts) 17 | { 18 | return 14 * sts; 19 | } 20 | -------------------------------------------------------------------------------- /ch02/getinfo.cpp: -------------------------------------------------------------------------------- 1 | // getinfo.cpp -- input and output 2 | #include 3 | 4 | int main() 5 | { 6 | using namespace std; 7 | 8 | int carrots; 9 | 10 | cout << "How many carrots do you have?" << endl; 11 | cin >> carrots; // C++ input 12 | cout << "Here are two more. "; 13 | carrots = carrots + 2; 14 | // the next line concatenates output 15 | cout << "Now you have " << carrots << " carrots." << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch02/myfirst.cpp: -------------------------------------------------------------------------------- 1 | // myfirst.cpp -- displays a message 2 | 3 | #include // a PREPROCESSOR directive 4 | int main() // function header 5 | { // start of function body 6 | using namespace std; // make definitions visible 7 | cout << "Come up and C++ me some time."; // message 8 | cout << endl; // start a new line 9 | cout << "You won't regret it!" << endl; // more output 10 | return 0; // terminate main() 11 | } // end of function body 12 | -------------------------------------------------------------------------------- /ch02/ourfunc.cpp: -------------------------------------------------------------------------------- 1 | // ourfunc.cpp -- defining your own function 2 | #include 3 | void simon(int); // function prototype for simon() 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | simon(3); // call the simon() function 9 | cout << "Pick an integer: "; 10 | int count; 11 | cin >> count; 12 | simon(count); // call it again 13 | cout << "Done!" << endl; 14 | return 0; 15 | } 16 | 17 | void simon(int n) // define the simon() function 18 | { 19 | using namespace std; 20 | cout << "Simon says touch your toes " << n << " times." << endl; 21 | } // void functions don't need return statements 22 | -------------------------------------------------------------------------------- /ch02/sqrt.cpp: -------------------------------------------------------------------------------- 1 | // sqrt.cpp -- using the sqrt() function 2 | 3 | #include 4 | #include // or math.h 5 | 6 | int main() 7 | { 8 | using namespace std; 9 | 10 | double area; 11 | cout << "Enter the floor area, in square feet, of your home: "; 12 | cin >> area; 13 | double side; 14 | side = sqrt(area); 15 | cout << "That's the equivalent of a square " << side 16 | << " feet to this side." << endl; 17 | cout << "How fascinating!" << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch03/arith.cpp: -------------------------------------------------------------------------------- 1 | // arith.cpp -- some C++ arithmetic 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | float hats, heads; 7 | 8 | cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point 9 | cout << "Enter a number: "; 10 | cin >> hats; 11 | cout << "Enter another number: "; 12 | cin >> heads; 13 | 14 | cout << "hats = " << hats << "; heads = " << heads << endl; 15 | cout << "hats + heads = " << hats + heads << endl; 16 | cout << "hats - heads = " << hats - heads << endl; 17 | cout << "hats * heads = " << hats * heads << endl; 18 | cout << "hats / heads = " << hats / heads << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ch03/bondini.cpp: -------------------------------------------------------------------------------- 1 | // bondini.cpp -- using escape sequences 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "\aOperation \"HyperHype\" is now activated!\n"; 7 | cout << "Enter your agent code:________\b\b\b\b\b\b\b\b"; 8 | long code; 9 | cin >> code; 10 | cout << "\aYou entered " << code << "...\n"; 11 | cout << "\aCode verified! Proceed with Plan Z3!\n"; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /ch03/chartype.cpp: -------------------------------------------------------------------------------- 1 | // chartype.cpp -- the char type 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | char ch; // declare a char variable 7 | 8 | cout << "Enter a character: " << endl; 9 | cin >> ch; 10 | cout << "Hola! "; 11 | cout << "Thank you for the " << ch << " character." << endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /ch03/divide.cpp: -------------------------------------------------------------------------------- 1 | // divide.cpp -- integer and floating-point division 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout.setf(ios_base::fixed, ios_base::floatfield); 7 | cout << "Integer division: 9/5 = " << 9 / 5 << endl; 8 | cout << "Floating-point division: 9.0/5.0 = "; 9 | cout << 9.0 / 5.0 << endl; 10 | cout << "Mixed division: 9.0/5 = " << 9.0 / 5 << endl; 11 | cout << "double constants: 1e7/9.0 = "; 12 | cout << 1.e7 / 9.0 << endl; 13 | cout << "float constants: 1e7f/9.0f = "; 14 | cout << 1.e7f / 9.0f << endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch03/floatnum.cpp: -------------------------------------------------------------------------------- 1 | // floatnum.cpp -- floating-point types 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point 7 | float tub = 10.0 / 3.0; // good to about 6 places 8 | double mint = 10.0 / 3.0; // good to about 15 places 9 | const float million = 1.0e6; 10 | 11 | cout << "tub = " << tub; 12 | cout << ", a million tubs = " << million * tub; 13 | cout << ",\nand ten million tubs = "; 14 | cout << 10 * million * tub << endl; 15 | 16 | cout << "mint = " << mint << " and a million mints = "; 17 | cout << million * mint << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch03/fltadd.cpp: -------------------------------------------------------------------------------- 1 | // fltadd.cpp -- precision problems with float 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | float a = 2.34E+22f; 7 | float b = a + 1.0f; 8 | 9 | cout << "a = " << a << endl; 10 | cout << "b - a = " << b - a << endl; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /ch03/hexoct1.cpp: -------------------------------------------------------------------------------- 1 | // hexoct1.cpp -- shows hex and octal literals 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int chest = 42; // decimal integer literal 7 | int waist = 0x42; // hexadecimal integer literal 8 | int inseam = 042; // octal integer literal 9 | 10 | cout << "Monsieur cuts a striking figure!\n"; 11 | cout << "chest = " << chest << " (42 in decimal)\n"; 12 | cout << "waist = " << waist << " (0x42 in hex)\n"; 13 | cout << "inseam = " << inseam << " (042 in octal)\n"; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /ch03/hexoct2.cpp: -------------------------------------------------------------------------------- 1 | // hexoct2.cpp -- display values in hex and octal 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | using namespace std; 7 | int chest = 42; 8 | int waist = 42; 9 | int inseam = 42; 10 | 11 | cout << "Monsieur cuts a striking figure!" << endl; 12 | cout << "chest = " << chest << " (decimal for 42)" << endl; 13 | cout << hex; // manipulator for changing number base 14 | cout << "waist = " << waist << " (hexadecimal for 42)" << endl; 15 | cout << oct; // manipulator for changing number base 16 | cout << "inseam = " << inseam << " (octal for 42)" << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /ch03/init.cpp: -------------------------------------------------------------------------------- 1 | // init.cpp -- type changes on initialization 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout.setf(ios_base::fixed, ios_base::floatfield); 7 | float tree = 3; // int converted to float 8 | int guess(3.9832); // double converted to float 9 | int debt = 7.2E12; // result not defined in C++ 10 | cout << "tree = " << tree << endl; 11 | cout << "guess = " << guess << endl; 12 | cout << "debt = " << debt << endl; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /ch03/modulus.cpp: -------------------------------------------------------------------------------- 1 | // modulus.cpp -- uses % operator to convert lbs to stone 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | const int Lbs_per_stn = 14; 7 | int lbs; 8 | 9 | cout << "Enter your weight in pounds: "; 10 | cin >> lbs; 11 | int stone = lbs / Lbs_per_stn; // whole stone 12 | int pounds = lbs % Lbs_per_stn; // remainder in pounds 13 | cout << lbs << " pounds are " << stone 14 | << " stone, " << pounds << " pound(s).\n"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch03/morechar.cpp: -------------------------------------------------------------------------------- 1 | // morechar.cpp -- the char type and int type contrasted 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | char ch = 'M'; // assign ASCII code for M to ch 7 | int i = ch; // store same code in an int 8 | cout << "The ASCII code for " << ch << " is " << i << endl; 9 | 10 | cout << "Add one to the character code:" << endl; 11 | ch = ch + 1; // change character code in ch 12 | i = ch; // save new character code in i 13 | cout << "The ASCII code for " << ch << " is " << i << endl; 14 | 15 | // using the cout.put() member function to display a char 16 | cout << "Displaying char ch using cout.put(ch): "; 17 | cout.put(ch); 18 | 19 | // using cout.put() to display a char constant 20 | cout.put('!'); 21 | 22 | cout << endl << "Done" << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /ch03/typecast.cpp: -------------------------------------------------------------------------------- 1 | // typecast.cpp -- forcing type changes 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int auks, bats, coots; 7 | 8 | // the following statement adds the values as double, 9 | // then converts the result to int 10 | auks = 19.99 + 11.99; 11 | 12 | // these statements add values as int 13 | bats = (int) 19.99 + (int) 11.99; // old C syntax 14 | coots = int (19.99) + int (11.99); // new C++ syntax 15 | cout << "auks = " << auks << ", bats = " << bats; 16 | cout << ", coots = " << coots << endl; 17 | 18 | char ch = 'Z'; 19 | cout << "The code for " << ch << " is "; // print as char 20 | cout << int(ch) << endl; // print as int 21 | cout << "Yes, the code is "; 22 | cout << static_cast(ch) << endl; // using static_cast 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /ch04/address.cpp: -------------------------------------------------------------------------------- 1 | // address.cpp -- using the & operator to find addresses 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int donuts = 6; 7 | double cups = 4.5; 8 | 9 | cout << "donuts value = " << donuts; 10 | cout << " and donuts address = " << &donuts << endl; 11 | // NOTE: you may need to use unsigned (&donuts) 12 | // and unsigned (&cups) 13 | cout << "cups value = " << cups; 14 | cout << " and cups address = " << &cups << endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch04/arraynew.cpp: -------------------------------------------------------------------------------- 1 | // arraynew.cpp -- using the new operator for arrays 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | double * p3 = new double [3]; // space for 3 doubles 7 | p3[0] = 0.2; // treat p3 like an array name 8 | p3[1] = 0.5; 9 | p3[2] = 0.8; 10 | cout << "p3[1] is " << p3[1] << ".\n"; 11 | p3 = p3 + 1; // increment the pointer 12 | cout << "Now p3[0] is " << p3[0] << " and "; 13 | cout << "p3[1] is " << p3[1] << ".\n"; 14 | p3 = p3 - 1; // point back to beginning 15 | delete [] p3; // free the memory 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch04/arrayone.cpp: -------------------------------------------------------------------------------- 1 | // arrayone.cpp -- small arrays of integers 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int yams[3]; // create array with three elements 7 | yams[0] = 7; // assign value to first element 8 | yams[1] = 8; 9 | yams[2] = 6; 10 | 11 | int yamcosts[3] = {20, 30, 5}; // create, initialize array 12 | // NOTE: If your C++ compiler or translator can't initialize 13 | // this array, use static int yamcosts[3] instead of 14 | // int yamcosts[3] 15 | 16 | cout << "Total yams = "; 17 | cout << yams[0] + yams[1] + yams[2] << endl; 18 | cout <<"The package with " << yams[1] << " yams costs "; 19 | cout << yamcosts[1] << " cents per yam.\n"; 20 | int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1]; 21 | total = total + yams[2] * yamcosts[2]; 22 | cout << "The total yam expense is " << total << " cents.\n"; 23 | 24 | cout << "\nSize of yams array = " << sizeof yams; 25 | cout << " bytes.\n"; 26 | cout << "Size of one element = " << sizeof yams[0]; 27 | cout << " bytes.\n"; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /ch04/arrstruc.cpp: -------------------------------------------------------------------------------- 1 | // arrstruc.cpp -- an array of structures 2 | #include 3 | struct inflatable 4 | { 5 | char name[20]; 6 | float volume; 7 | double price; 8 | }; 9 | int main() 10 | { 11 | using namespace std; 12 | inflatable guests[2] = // initializing an array of structs 13 | { 14 | {"Bambi", 0.5, 21.99}, // first structure in array 15 | {"Godzilla", 2000, 565.99} // next structure in array 16 | }; 17 | 18 | cout << "The guests " << guests[0].name << " and " << guests[1].name 19 | << "\nhave a combined volume of " 20 | << guests[0].volume + guests[1].volume << " cubic feet.\n"; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch04/assgn_st.cpp: -------------------------------------------------------------------------------- 1 | // assgn_st.cpp -- assigning structures 2 | #include 3 | struct inflatable 4 | { 5 | char name[20]; 6 | float volume; 7 | double price; 8 | }; 9 | int main() 10 | { 11 | using namespace std; 12 | inflatable bouquet = 13 | { 14 | "sunflowers", 15 | 0.20, 16 | 12.49 17 | }; 18 | inflatable choice; 19 | cout << "bouquet: " << bouquet.name << " for $"; 20 | cout << bouquet.price << endl; 21 | 22 | choice = bouquet; // assign one structure to another 23 | cout << "choice: " << choice.name << " for $"; 24 | cout << choice.price << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /ch04/delete.cpp: -------------------------------------------------------------------------------- 1 | // delete.cpp -- using the delete operation 2 | #include 3 | #include // or string.h 4 | using namespace std; 5 | char * getname(void); // function prototype 6 | int main() 7 | { 8 | char * name; // create pointer but no storage 9 | 10 | name = getname(); // assign address of string to name 11 | cout << name << " at " << (int *) name << "\n"; 12 | delete [] name; // memory freed 13 | 14 | name = getname(); // reuse freed memory 15 | cout << name << " at " << (int *) name << "\n"; 16 | delete [] name; // memory freed again 17 | return 0; 18 | } 19 | 20 | char * getname() // return pointer to new string 21 | { 22 | char temp[80]; // temporary storage 23 | cout << "Enter last name: "; 24 | cin >> temp; 25 | char * pn = new char[strlen(temp) + 1]; 26 | strcpy(pn, temp); // copy string into smaller space 27 | 28 | return pn; // temp lost when function ends 29 | } 30 | -------------------------------------------------------------------------------- /ch04/init_ptr.cpp: -------------------------------------------------------------------------------- 1 | // init_ptr.cpp -- initialize a pointer 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int higgens = 5; 7 | int * pt = &higgens; 8 | 9 | cout << "Value of higgens = " << higgens 10 | << "; Address of higgens = " << &higgens << endl; 11 | cout << "Value of *pt = " << *pt 12 | << "; Value of pt = " << pt << endl; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /ch04/instr1.cpp: -------------------------------------------------------------------------------- 1 | // instr1.cpp -- reading more than one string 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | const int ArSize = 20; 7 | char name[ArSize]; 8 | char dessert[ArSize]; 9 | 10 | cout << "Enter your name:\n"; 11 | cin >> name; 12 | cout << "Enter your favorite dessert:\n"; 13 | cin >> dessert; 14 | cout << "I have some delicious " << dessert; 15 | cout << " for you, " << name << ".\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch04/instr2.cpp: -------------------------------------------------------------------------------- 1 | // instr2.cpp -- reading more than one word with getline 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | const int ArSize = 20; 7 | char name[ArSize]; 8 | char dessert[ArSize]; 9 | 10 | cout << "Enter your name:\n"; 11 | cin.getline(name, ArSize); // reads through newline 12 | cout << "Enter your favorite dessert:\n"; 13 | cin.getline(dessert, ArSize); 14 | cout << "I have some delicious " << dessert; 15 | cout << " for you, " << name << ".\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch04/instr3.cpp: -------------------------------------------------------------------------------- 1 | // instr3.cpp -- reading more than one word with get() & get() 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | const int ArSize = 20; 7 | char name[ArSize]; 8 | char dessert[ArSize]; 9 | 10 | cout << "Enter your name:\n"; 11 | cin.get(name, ArSize).get(); // read string, newline 12 | cout << "Enter your favorite dessert:\n"; 13 | cin.get(dessert, ArSize).get(); 14 | cout << "I have some delicious " << dessert; 15 | cout << " for you, " << name << ".\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch04/mixtypes.cpp: -------------------------------------------------------------------------------- 1 | // mixtypes.cpp -- some type combinations 2 | #include 3 | 4 | struct antarctica_years_end 5 | { 6 | int year; 7 | /* some really interesting data, etc. */ 8 | }; 9 | 10 | int main() 11 | { 12 | antarctica_years_end s01, s02, s03; 13 | s01.year = 1998; 14 | antarctica_years_end * pa = &s02; 15 | pa->year = 1999; 16 | antarctica_years_end trio[3]; // array of 3 structures 17 | trio[0].year = 2003; 18 | std::cout << trio->year << std::endl; 19 | const antarctica_years_end * arp[3] = {&s01, &s02, &s03}; 20 | std::cout << arp[1]->year << std::endl; 21 | const antarctica_years_end ** ppa = arp; 22 | auto ppb = arp; // C++11 automatic type deduction 23 | // or else use const antarctica_years_end ** ppb = arp; 24 | std::cout << (*ppa)->year << std::endl; 25 | std::cout << (*(ppb+1))->year << std::endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /ch04/newstrct.cpp: -------------------------------------------------------------------------------- 1 | // newstrct.cpp -- using new with a structure 2 | #include 3 | struct inflatable // structure definition 4 | { 5 | char name[20]; 6 | float volume; 7 | double price; 8 | }; 9 | int main() 10 | { 11 | using namespace std; 12 | inflatable * ps = new inflatable; // allot memory for structure 13 | cout << "Enter name of inflatable item: "; 14 | cin.get(ps->name, 20); // method 1 for member access 15 | cout << "Enter volume in cubic feet: "; 16 | cin >> (*ps).volume; // method 2 for member access 17 | cout << "Enter price: $"; 18 | cin >> ps->price; 19 | cout << "Name: " << (*ps).name << endl; // method 2 20 | cout << "Volume: " << ps->volume << " cubic feet\n";// method 1 21 | cout << "Price: $" << ps->price << endl; // method 1 22 | delete ps; // free memory used by structure 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /ch04/numstr.cpp: -------------------------------------------------------------------------------- 1 | // numstr.cpp -- following number input with line input 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "What year was your house built?\n"; 7 | int year; 8 | cin >> year; 9 | cout << "What is its street address?\n"; 10 | char address[80]; 11 | cin.getline(address, 80); 12 | cout << "Year built: " << year << endl; 13 | cout << "Address: " << address << endl; 14 | cout << "Done!\n"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch04/pointer.cpp: -------------------------------------------------------------------------------- 1 | // pointer.cpp -- our first pointer variable 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int updates = 6; // declare a variable 7 | int * p_updates; // declare pointer to an int 8 | p_updates = &updates; // assign address of int to pointer 9 | 10 | // express values two ways 11 | cout << "Values: updates = " << updates; 12 | cout << ", *p_updates = " << *p_updates << endl; 13 | 14 | // express address two ways 15 | cout << "Address: &updates = " << &updates; 16 | cout << ", p_updates = " << p_updates << endl; 17 | 18 | // use pointer to change value 19 | *p_updates = *p_updates + 1; 20 | cout << "Now updates = " << updates << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch04/strings.cpp: -------------------------------------------------------------------------------- 1 | // strings.cpp -- storing strings in an array 2 | #include 3 | #include // for the strlen() function 4 | int main() 5 | { 6 | using namespace std; 7 | const int Size = 15; 8 | char name1[Size]; // empty array 9 | char name2[Size] = "C++owboy"; // initialized array 10 | // NOTE: some implementations may require the static keyword 11 | // to initialize the array name2 12 | 13 | cout << "Howdy! I'm " << name2; 14 | cout << "! What's your name?\n"; 15 | cin >> name1; 16 | cout << "Well, " << name1 << ", your name has "; 17 | cout << strlen(name1) << " letters and is stored\n"; 18 | cout << "in an array of " << sizeof(name1) << " bytes.\n"; 19 | cout << "Your initial is " << name1[0] << ".\n"; 20 | name2[3] = '\0'; // set to null character 21 | 22 | cout << "Here are the first 3 characters of my name: "; 23 | cout << name2 << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /ch04/strtype1.cpp: -------------------------------------------------------------------------------- 1 | // strtype1.cpp -- using the C++ string class 2 | #include 3 | #include // make string class available 4 | int main() 5 | { 6 | using namespace std; 7 | char charr1[20]; // create an empty array 8 | char charr2[20] = "jaguar"; // create an initialized array 9 | string str1; // create an empty string object 10 | string str2 = "panther"; // create an initialized string 11 | 12 | cout << "Enter a kind of feline: "; 13 | cin >> charr1; 14 | cout << "Enter another kind of feline: "; 15 | cin >> str1; // use cin for input 16 | cout << "Here are some felines:\n"; 17 | cout << charr1 << " " << charr2 << " " 18 | << str1 << " " << str2 // use cout for output 19 | << endl; 20 | cout << "The third letter in " << charr2 << " is " 21 | << charr2[2] << endl; 22 | cout << "The third letter in " << str2 << " is " 23 | << str2[2] << endl; // use array notation 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /ch04/strtype2.cpp: -------------------------------------------------------------------------------- 1 | // strtype2.cpp -- assigning, adding, and appending 2 | #include 3 | #include // make string class available 4 | int main() 5 | { 6 | using namespace std; 7 | string s1 = "penguin"; 8 | string s2, s3; 9 | 10 | cout << "You can assign one string object to another: s2 = s1\n"; 11 | s2 = s1; 12 | cout << "s1: " << s1 << ", s2: " << s2 << endl; 13 | cout << "You can assign a C-style string to a string object.\n"; 14 | cout << "s2 = \"buzzard\"\n"; 15 | s2 = "buzzard"; 16 | cout << "s2: " << s2 << endl; 17 | cout << "You can concatenate strings: s3 = s1 + s2\n"; 18 | s3 = s1 + s2; 19 | cout << "s3: " << s3 << endl; 20 | cout << "You can append strings.\n"; 21 | s1 += s2; 22 | cout << "s1 += s2 yields s1 = " << s1 << endl; 23 | s2 += " for a day"; 24 | cout << "s2 += \" for a day\" yields s2 = " << s2 << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /ch04/strtype4.cpp: -------------------------------------------------------------------------------- 1 | // strtype4.cpp -- line input 2 | #include 3 | #include // make string class available 4 | #include // C-style string library 5 | int main() 6 | { 7 | using namespace std; 8 | char charr[20]; 9 | string str; 10 | 11 | cout << "Length of string in charr before input: " 12 | << strlen(charr) << endl; 13 | cout << "Length of string in str before input: " 14 | << str.size() << endl; 15 | cout << "Enter a line of text:\n"; 16 | cin.getline(charr, 20); // indicate maximum length 17 | cout << "You entered: " << charr << endl; 18 | cout << "Enter another line of text:\n"; 19 | getline(cin, str); // cin now an argument; no length specifier 20 | cout << "You entered: " << str << endl; 21 | cout << "Length of string in charr after input: " 22 | << strlen(charr) << endl; 23 | cout << "Length of string in str after input: " 24 | << str.size() << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /ch04/structur.cpp: -------------------------------------------------------------------------------- 1 | // structur.cpp -- a simple structure 2 | #include 3 | struct inflatable // structure declaration 4 | { 5 | char name[20]; 6 | float volume; 7 | double price; 8 | }; 9 | 10 | int main() 11 | { 12 | using namespace std; 13 | inflatable guest = 14 | { 15 | "Glorious Gloria", // name value 16 | 1.88, // volume value 17 | 29.99 // price value 18 | }; // guest is a structure variable of type inflatable 19 | // It's initialized to the indicated values 20 | inflatable pal = 21 | { 22 | "Audacious Arthur", 23 | 3.12, 24 | 32.99 25 | }; // pal is a second variable of type inflatable 26 | // NOTE: some implementations require using 27 | // static inflatable guest 28 | 29 | cout << "Expand your guest list with " << guest.name; 30 | cout << " and " << pal.name << "!\n"; 31 | // pal.name is the name member of the pal variable 32 | cout << "You can have both for $"; 33 | cout << guest.price + pal.price << "!\n"; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /ch04/use_new.cpp: -------------------------------------------------------------------------------- 1 | // use_new.cpp -- using the new operator 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int nights = 1001; 7 | int * pt = new int; // allocate space for an int 8 | *pt = 1001; // store a value there 9 | 10 | cout << "nights value = "; 11 | cout << nights << ": location " << &nights << endl; 12 | cout << "int "; 13 | cout << "value = " << *pt << ": location = " << pt << endl; 14 | double * pd = new double; // allocate space for a double 15 | *pd = 10000001.0; // store a double there 16 | 17 | cout << "double "; 18 | cout << "value = " << *pd << "; location = " << pd << endl; 19 | cout << "location of pointer pd: " << &pd << endl; 20 | cout << "size of pt = " << sizeof(pt); 21 | cout << "; size of *pt = " << sizeof(*pt) << endl; 22 | cout << "size of pd = " << sizeof pd; 23 | cout << "; size of *pd = " << sizeof(*pd) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /ch05/bigstep.cpp: -------------------------------------------------------------------------------- 1 | // bigstep.cpp -- count as directed 2 | #include 3 | int main() 4 | { 5 | using std::cout; // a using declaration 6 | using std::cin; 7 | using std::endl; 8 | cout << "Enter an integer: "; 9 | int by; 10 | cin >> by; 11 | cout << "Counting by " << by << "s:\n"; 12 | for (int i = 0; i < 100; i = i + by) 13 | cout << i << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /ch05/block.cpp: -------------------------------------------------------------------------------- 1 | // block.cpp -- use a block statement 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "The Amazing Accounto will sum and average "; 7 | cout << "five numbers for you.\n"; 8 | cout << "Please enter five values:\n"; 9 | double number; 10 | double sum = 0.0; 11 | for (int i = 1; i <= 5; i++) 12 | { // blocks starts here 13 | cout << "Value " << i << ": "; 14 | cin >> number; 15 | sum += number; 16 | } // blocks ends here 17 | cout << "Five exquisite choices indeed! "; 18 | cout << "They sum to " << sum << endl; 19 | cout << "and average to " << sum / 5 << ".\n"; 20 | cout << "The Amazing Accounto bids you adieu!\n"; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch05/compstr1.cpp: -------------------------------------------------------------------------------- 1 | // compstr1.cpp -- comparing strings using arrays 2 | #include 3 | #include // prototype for strcmp() 4 | int main() 5 | { 6 | using namespace std; 7 | char word[5] = "?ate"; 8 | for (char ch = 'a'; strcmp(word, "mate"); ch++) 9 | { 10 | cout << word << endl; 11 | word[0] = ch; 12 | } 13 | cout << "After loop ends, word is " << word << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /ch05/compstr2.cpp: -------------------------------------------------------------------------------- 1 | // compstr2.cpp -- comparing strings using arrays 2 | #include 3 | #include // string class 4 | int main() 5 | { 6 | using namespace std; 7 | string word = "?ate"; 8 | for (char ch = 'a'; word != "mate"; ch++) 9 | { 10 | cout << word << endl; 11 | word[0] = ch; 12 | } 13 | cout << "After loop ends, word is " << word << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /ch05/dowhile.cpp: -------------------------------------------------------------------------------- 1 | // dowhile.cpp -- exit-condition loop 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int n; 7 | 8 | cout << "Enter numbers in the range 1-10 to find "; 9 | cout << "my favorite number\n"; 10 | do 11 | { 12 | cin >> n; // execute body 13 | } while (n != 7); // then test 14 | cout << "Yes, 7 is my favorite.\n"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch05/equal.cpp: -------------------------------------------------------------------------------- 1 | // equal.cpp -- equality vs assignment 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int quizscores[10] = 7 | { 20, 20, 20, 20, 20, 19, 20, 18, 20, 20}; 8 | 9 | cout << "Doing it right:\n"; 10 | int i; 11 | for (i = 0; quizscores[i] == 20; i++) 12 | cout << "quiz " << i << " is a 20\n"; 13 | // Warning: you may prefer reading about this program 14 | // to actually running it. 15 | cout << "Doing it dangerously wrong:\n"; 16 | for (i = 0; quizscores[i] = 20; i++) 17 | cout << "quiz " << i << " is a 20\n"; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ch05/express.cpp: -------------------------------------------------------------------------------- 1 | // express.cpp -- values of expressions 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int x; 7 | 8 | cout << "The expression x = 100 has the value "; 9 | cout << (x = 100) << endl; 10 | cout << "Now x = " << x << endl; 11 | cout << "The expression x < 3 has the value "; 12 | cout << (x < 3) << endl; 13 | cout << "The expression x > 3 has the value "; 14 | cout << (x > 3) << endl; 15 | cout.setf(ios_base::boolalpha); // a newer C++ feature 16 | cout << "The expression x < 3 has the value "; 17 | cout << (x < 3) << endl; 18 | cout << "The expression x > 3 has the value "; 19 | cout << (x > 3) << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /ch05/forloop.cpp: -------------------------------------------------------------------------------- 1 | // forloop.cpp -- introducing the for loop 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int i; // create a counter 7 | // initialize; test; update 8 | for (i = 0; i < 5; i++) 9 | cout << "C++ knows loops.\n"; 10 | cout << "C++ knows when to stop.\n"; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /ch05/formore.cpp: -------------------------------------------------------------------------------- 1 | // formore.cpp -- more looping with for 2 | #include 3 | const int ArSize = 16; // example of external declaration 4 | int main() 5 | { 6 | long long factorials[ArSize]; 7 | factorials[1] = factorials[0] = 1LL; 8 | for (int i = 2; i < ArSize; i++) 9 | factorials[i] = i * factorials[i-1]; 10 | for (int i = 0; i < ArSize; i++) 11 | std::cout << i << "! = " << factorials[i] << std::endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /ch05/forstr1.cpp: -------------------------------------------------------------------------------- 1 | // forstr1.cpp -- using for with a string 2 | #include 3 | #include 4 | int main() 5 | { 6 | using namespace std; 7 | cout << "Enter a word: "; 8 | string word; 9 | cin >> word; 10 | 11 | // display letters in reverse order 12 | for (int i = word.size() - 1; i >= 0; i--) 13 | cout << word[i]; 14 | cout << "\nBye.\n"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch05/forstr2.cpp: -------------------------------------------------------------------------------- 1 | // forstr2.cpp -- reversing an array 2 | #include 3 | #include 4 | int main() 5 | { 6 | using namespace std; 7 | cout << "Enter a word: "; 8 | string word; 9 | cin >> word; 10 | 11 | // physically modify string object 12 | char temp; 13 | int i, j; 14 | for (j = 0, i = word.size() - 1; j < i; --i, ++j) 15 | { // start block 16 | temp = word[i]; 17 | word[i] = word[j]; 18 | word[j] = temp; 19 | } // end block 20 | cout << word << "\nDone\n"; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch05/num_test.cpp: -------------------------------------------------------------------------------- 1 | // num_test.cpp -- use numeric test in for loop 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "Enter the starting countdown value: "; 7 | int limit; 8 | cin >> limit; 9 | int i; 10 | for (i = limit; i; i--) // quits when i is 0 11 | cout << "i = " << i << "\n"; 12 | cout << "Done now that i = " << i << "\n"; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /ch05/plus_one.cpp: -------------------------------------------------------------------------------- 1 | // plus_one.cpp -- the increment operator 2 | #include 3 | int main() 4 | { 5 | using std::cout; 6 | int a = 20; 7 | int b = 20; 8 | cout << "a = " << a << "; b = " << b << "\n"; 9 | cout << "a++ = " << a++ << "; ++b = " << ++b << "\n"; 10 | cout << "a = " << a << "; b = " << b << "\n"; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /ch05/textin1.cpp: -------------------------------------------------------------------------------- 1 | // textin1.cpp -- reading chars with a while loop 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | char ch; 7 | int count = 0; // use basic input 8 | cout << "Enter characters; enter # to quit:\n"; 9 | cin >> ch; // get a character 10 | while (ch != '#') // test the character 11 | { 12 | cout << ch; // echo the character 13 | ++count; // count the character 14 | cin >> ch; // get the next character 15 | } 16 | cout << endl << count << " characters read\n"; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /ch05/textin2.cpp: -------------------------------------------------------------------------------- 1 | // textin2.cpp -- using cin.get(char) 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | char ch; 7 | int count = 0; 8 | 9 | cout << "Enter characters; enter # to quit:\n"; 10 | cin.get(ch); // use the cin.get(ch) function 11 | while (ch != '#') 12 | { 13 | cout << ch; 14 | ++count; 15 | cin.get(ch); // use it again 16 | } 17 | cout << endl << count << " characters read\n"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch05/textin3.cpp: -------------------------------------------------------------------------------- 1 | // textin3.cpp -- reading chars to end of file 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | char ch; 7 | int count = 0; 8 | cin.get(ch); // attempt to read a char 9 | while (cin.fail() == false) // test for EOF 10 | { 11 | cout << ch; // echo character 12 | ++count; 13 | cin.get(ch); // attempt to read another char 14 | } 15 | cout << endl << count << " characters read\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch05/textin4.cpp: -------------------------------------------------------------------------------- 1 | // textin4.cpp -- reading data with cin.get() 2 | #include 3 | #include 4 | int main(void) 5 | { 6 | using namespace std; 7 | int ch; // should be int, not char 8 | int count = 0; 9 | 10 | while ((ch = cin.get()) != EOF) // test for end-of-file 11 | { 12 | cout.put(char(ch)); 13 | ++count; 14 | } 15 | cout << endl << count << " characters read\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch05/waiting.cpp: -------------------------------------------------------------------------------- 1 | // waiting.cpp -- using clock() in a time-delay loop 2 | #include 3 | #include // describes clock() function, clock_t type 4 | int main() 5 | { 6 | using namespace std; 7 | cout << "Enter the delay time, in seconds: "; 8 | float secs; 9 | cin >> secs; 10 | clock_t delay = secs * CLOCKS_PER_SEC; // convert to clock ticks 11 | cout << "starting\a\n"; 12 | clock_t start = clock(); 13 | while (clock() - start < delay) // wait until time elapses 14 | ; // note the semicolon 15 | cout << "done \a\n"; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /ch05/while.cpp: -------------------------------------------------------------------------------- 1 | // while.cpp -- introducing the while loop 2 | #include 3 | const int ArSize = 20; 4 | int main() 5 | { 6 | using namespace std; 7 | char name[ArSize]; 8 | cout << "Your first name, please: "; 9 | cin >> name; 10 | cout << "Here is your name, verticalized and ASCIIized:\n"; 11 | int i = 0; // start at beginning of string 12 | while (name[i] != '\0') // process to end of string 13 | { 14 | cout << name[i] << ": " << int(name[i]) << endl; 15 | i++; // don't forget this step 16 | } 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /ch06/carinfo.txt: -------------------------------------------------------------------------------- 1 | Make and model: Flitz Perky 2 | Year: 2009 3 | Was asking $13500.00 4 | Now asking $12325.50 5 | -------------------------------------------------------------------------------- /ch06/cinfish.cpp: -------------------------------------------------------------------------------- 1 | // cinfish.cpp -- non-numeric input terminates loop 2 | #include 3 | const int Max = 5; 4 | int main() 5 | { 6 | using namespace std; 7 | // get date 8 | double fish[Max]; 9 | cout << "Please enter the weights of your fish.\n"; 10 | cout << "You may enter up to " << Max 11 | << " fish .\n"; 12 | cout << "fish #1: "; 13 | int i = 0; 14 | while (i < Max && cin >> fish[i]) { 15 | if (++i < Max) 16 | cout << "fish #" << i+1 << ": "; 17 | } 18 | // calculate average 19 | double total = 0.0; 20 | for (int j = 0; j < i; j++) 21 | total += fish[j]; 22 | // report results 23 | if (i == 0) 24 | cout << "No fish\n"; 25 | else 26 | cout << total / i << " = average weight of " 27 | << i << " fish\n"; 28 | cout << "Done.\n"; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /ch06/cingolf.cpp: -------------------------------------------------------------------------------- 1 | // cingolf.cpp -- non-numeric input skipped 2 | #include 3 | const int Max = 5; 4 | int main() 5 | { 6 | using namespace std; 7 | // get data 8 | int golf[Max]; 9 | cout << "Please enter your scores.\n"; 10 | cout << "You must enter " << Max << " rounds.\n"; 11 | int i; 12 | for (i = 0; i < Max; i++) 13 | { 14 | cout << "round #" << i+1 << ": "; 15 | while (!(cin >> golf[i])) { 16 | cin.clear(); // reset input 17 | while (cin.get() != '\n') 18 | continue; // get rid of bad input 19 | cout << "Please enter a number: "; 20 | } 21 | } 22 | // calculate average 23 | double total = 0.0; 24 | for (i = 0; i < Max; i++) 25 | total += golf[i]; 26 | // report results 27 | cout << total / Max << " = average score " 28 | << Max << " rounds\n"; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /ch06/condit.cpp: -------------------------------------------------------------------------------- 1 | // condit.cpp -- using the conditional operator 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int a, b; 7 | cout << "Enter two integers: "; 8 | cin >> a >> b; 9 | cout << "The larger of " << a << " and " << b; 10 | int c = a > b ? a : b; // c = a if a > b, else c = b 11 | cout << " is " << c << endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /ch06/enum.cpp: -------------------------------------------------------------------------------- 1 | // enum.cpp -- using enum 2 | #include 3 | // create named constants for 0 - 6 4 | enum {red, orange, yellow, green, blue, violet, indigo}; 5 | 6 | int main() 7 | { 8 | using namespace std; 9 | cout << "Enter color code (0-6): "; 10 | int code; 11 | cin >> code; 12 | while (code >= red && code <= indigo) 13 | { 14 | switch (code) 15 | { 16 | case red : cout << "Her lips were red.\n"; break; 17 | case orange : cout << "Her hair was orange.\n"; break; 18 | case yellow : cout << "Her shoes were yellow.\n"; break; 19 | case green : cout << "Her nails were green.\n"; break; 20 | case blue : cout << "Her sweatsuit was blue.\n"; break; 21 | case violet : cout << "Her eyes were violet.\n"; break; 22 | case indigo : cout << "Her mood was indigo.\n"; break; 23 | } 24 | cout << "Enter color code (0-6): "; 25 | cin >> code; 26 | } 27 | cout << "Bye\n"; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /ch06/if.cpp: -------------------------------------------------------------------------------- 1 | // if.cpp -- using the if statement 2 | #include 3 | int main() 4 | { 5 | using std::cin; // using declarations 6 | using std::cout; 7 | char ch; 8 | int spaces = 0; 9 | int total = 0; 10 | cin.get(ch); 11 | while (ch != '.') // quit at end of sentence 12 | { 13 | if (ch == ' ') // check if ch is a space 14 | ++spaces; 15 | ++total; // done every time 16 | cin.get(ch); 17 | } 18 | cout << spaces << " spaces, " << total; 19 | cout << " characters total in sentence\n"; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /ch06/ifelse.cpp: -------------------------------------------------------------------------------- 1 | // ifelse.cpp -- using the if else statement 2 | #include 3 | int main() 4 | { 5 | char ch; 6 | 7 | std::cout << "Type, and I shall repeat.\n"; 8 | std::cin.get(ch); 9 | while (ch != '.') 10 | { 11 | if (ch == '\n') 12 | std::cout << ch; // done if newline 13 | else 14 | std::cout << ++ch; // done otherwise 15 | std::cin.get(ch); 16 | } 17 | // try ch + 1 instead of ++ch for interesting effect 18 | std::cout << "\nPlease excuse the slight confusion.\n"; 19 | // std::cin.get(); 20 | // std::cin.get(); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch06/ifelseif.cpp: -------------------------------------------------------------------------------- 1 | // ifelseif.cpp -- using if else if else 2 | #include 3 | const int Fave = 27; 4 | int main() 5 | { 6 | using namespace std; 7 | int n; 8 | 9 | cout << "Enter a number in the range 1-100 to find "; 10 | cout << "my favorite number: "; 11 | do 12 | { 13 | cin >> n; 14 | if (n < Fave) 15 | cout << "Too low -- guess again: "; 16 | else if (n > Fave) 17 | cout << "Too high -- guess again: "; 18 | else 19 | cout << Fave << " is right!\n"; 20 | } while (n != Fave); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch06/jump.cpp: -------------------------------------------------------------------------------- 1 | // jump.cpp -- using continue and break 2 | #include 3 | const int ArSize = 80; 4 | int main() 5 | { 6 | using namespace std; 7 | char line[ArSize]; 8 | int spaces = 0; 9 | 10 | cout << "Enter a line of text:\n"; 11 | cin.get(line, ArSize); 12 | cout << "Complete line:\n" << line << endl; 13 | cout << "Line through first period:\n"; 14 | for (int i = 0; line[i] != '\0'; i++) 15 | { 16 | cout << line[i]; // display character 17 | if (line[i] == '.') // quit if it's a period 18 | break; 19 | if (line[i] != ' ') // skip rest of loop 20 | continue; 21 | spaces++; 22 | } 23 | cout << "\n" << spaces << " spaces\n"; 24 | cout << "Done.\n"; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /ch06/more_and.cpp: -------------------------------------------------------------------------------- 1 | // more_and.cpp -- using the logical AND operator 2 | #include 3 | const char * qualify[4] = // an array of pointers 4 | { // to strings 5 | "10,000-meter race.\n", 6 | "mud tug-of-war.\n", 7 | "masters canor jousting.\n", 8 | "pie-throwing festival.\n" 9 | }; 10 | int main() 11 | { 12 | using namespace std; 13 | int age; 14 | cout << "Enter your age in years: "; 15 | cin >> age; 16 | int index; 17 | 18 | if (age > 17 && age < 35) 19 | index = 0; 20 | else if (age >= 35 && age < 50) 21 | index = 1; 22 | else if (age >= 50 && age < 65) 23 | index = 2; 24 | else 25 | index = 3; 26 | 27 | cout << "You qualify for the " << qualify[index]; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /ch06/not.cpp: -------------------------------------------------------------------------------- 1 | // not.cpp -- using the not operator 2 | #include 3 | #include 4 | bool is_int(double); 5 | int main() 6 | { 7 | using namespace std; 8 | double num; 9 | 10 | cout << "Yo, dude! Enter an integer value: "; 11 | cin >> num; 12 | while (!is_int(num)) // continue while num is not int-able 13 | { 14 | cout << "Out of range -- please try again: "; 15 | cin >> num; 16 | } 17 | int val = int (num); // type cast 18 | cout << "You've entered the integer " << val << "\nBye\n"; 19 | return 0; 20 | } 21 | 22 | bool is_int(double x) 23 | { 24 | if (x <= INT_MAX && x >= INT_MIN) // use climits values 25 | return true; 26 | else 27 | return false; 28 | } 29 | -------------------------------------------------------------------------------- /ch06/or.cpp: -------------------------------------------------------------------------------- 1 | // or.cpp -- using the logical OR operator 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | cout << "This program may reformat your hard disk\n" 7 | "and destroy all your data.\n" 8 | "Do you wish to continue? "; 9 | char ch; 10 | cin >> ch; 11 | if (ch == 'y' || ch == 'Y') // y or Y 12 | cout << "You were warned!\a\a\n"; 13 | else if (ch == 'n' || ch == 'N') // n or N 14 | cout << "A wise choice ... bye\n"; 15 | else 16 | cout << "That wasn't a y or n! Apparently you " 17 | "can't follow\ninstructions, so " 18 | "I'll trash your disk anyway.\a\a\a\n"; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ch06/scores.txt: -------------------------------------------------------------------------------- 1 | 18 19 18.5 13.5 14 2 | 16 19.5 20 18 12 18.5 3 | 17.5 4 | -------------------------------------------------------------------------------- /ch07/arrfun1.cpp: -------------------------------------------------------------------------------- 1 | // arrfun1.cpp -- functions with an array argument 2 | #include 3 | const int ArSize = 8; 4 | int sum_arr(int arr[], int n); // prototype 5 | int main() 6 | { 7 | using namespace std; 8 | int cookies[ArSize] = {1,2,4,8,16,32,64,128}; 9 | // some system require preceding int with static to 10 | // enable array initialization 11 | 12 | int sum = sum_arr(cookies, ArSize); 13 | cout << "Total cookies eaten: " << sum << "\n"; 14 | return 0; 15 | } 16 | 17 | // return the sum of an integer array 18 | int sum_arr(int arr[], int n) 19 | { 20 | int total = 0; 21 | for (int i = 0; i < n; i++) 22 | total = total + arr[i]; 23 | return total; 24 | } 25 | -------------------------------------------------------------------------------- /ch07/arrfun4.cpp: -------------------------------------------------------------------------------- 1 | // arrfun4.cpp -- functions with an array range 2 | #include 3 | const int ArSize = 8; 4 | int sum_arr(const int * begin, const int * end); 5 | int main() 6 | { 7 | using namespace std; 8 | int cookies[ArSize] = {1,2,4,8,16,32,64,128}; 9 | // some systems require preceding int with static to 10 | // enable array initialization 11 | 12 | int sum = sum_arr(cookies, cookies + ArSize); 13 | cout << "Total cookies eaten: " << sum << endl; 14 | sum = sum_arr(cookies, cookies + 3); // first 3 elements 15 | cout << "First three eaters ate " << sum << " cookies.\n"; 16 | sum = sum_arr(cookies + 4, cookies + 8); // last 4 elements 17 | cout << "Last four eaters ate " << sum << " cookies.\n"; 18 | return 0; 19 | } 20 | 21 | // return the sum of an integer array 22 | int sum_arr(const int * begin, const int * end) 23 | { 24 | const int * pt; 25 | int total = 0; 26 | 27 | for (pt = begin; pt != end; pt++) 28 | total = total + *pt; 29 | return total; 30 | } 31 | -------------------------------------------------------------------------------- /ch07/calling.cpp: -------------------------------------------------------------------------------- 1 | // calling.cpp -- defining, prototyping, and calling a function 2 | #include 3 | void simple(); // function prototype 4 | 5 | int main() 6 | { 7 | using namespace std; 8 | cout << "main() will call the simple() function:\n"; 9 | simple(); // function call 10 | cout << "main() is finished with the simple() function.\n"; 11 | // cin.get(); 12 | return 0; 13 | } 14 | 15 | // function definition 16 | void simple() 17 | { 18 | using namespace std; 19 | cout << "I'm but a simple function.\n"; 20 | } 21 | -------------------------------------------------------------------------------- /ch07/fun_ptr.cpp: -------------------------------------------------------------------------------- 1 | // fun_ptr.cpp -- pointers to functions 2 | #include 3 | double betsy(int); 4 | double pam(int); 5 | 6 | // second argument is pointer to a type double function that 7 | // takes a type int argument 8 | void estimate(int lines, double (*pf)(int)); 9 | 10 | int main() 11 | { 12 | using namespace std; 13 | int code; 14 | cout << "How many lines of code do you need? "; 15 | cin >> code; 16 | cout << "Here's Betsy's estimate:\n"; 17 | estimate(code, betsy); 18 | cout << "Here's Pam's estimate:\n"; 19 | estimate(code, pam); 20 | return 0; 21 | } 22 | 23 | double betsy(int lns) 24 | { 25 | return 0.05 * lns; 26 | } 27 | 28 | double pam(int lns) 29 | { 30 | return 0.03 * lns + 0.0004 * lns * lns; 31 | } 32 | 33 | void estimate(int lines, double (*pf)(int)) 34 | { 35 | using namespace std; 36 | cout << lines << " lines will take "; 37 | cout << (*pf)(lines) << " hour(s)\n"; 38 | } 39 | -------------------------------------------------------------------------------- /ch07/protos.cpp: -------------------------------------------------------------------------------- 1 | // protos.cpp -- using prototypes and function calls 2 | #include 3 | void cheers(int); // prototype: no return value 4 | double cube(double x); // prototype: returns a double 5 | int main() 6 | { 7 | using namespace std; 8 | cheers(5); // function call 9 | double side; 10 | cin >> side; 11 | double volume = cube(side); // function call 12 | cout << "A " << side << " foot cube has a volume of "; 13 | cout << volume << " cubic feet.\n"; 14 | cheers(cube(2)); // prptotype protection at work 15 | return 0; 16 | } 17 | 18 | void cheers(int n) 19 | { 20 | using namespace std; 21 | for (int i = 0; i < n; i++) 22 | cout << "Cheers! "; 23 | cout << endl; 24 | } 25 | 26 | double cube(double x) 27 | { 28 | return x * x * x; 29 | } 30 | -------------------------------------------------------------------------------- /ch07/recur.cpp: -------------------------------------------------------------------------------- 1 | // recur.cpp -- using recursion 2 | #include 3 | void countdown(int n); 4 | 5 | int main() 6 | { 7 | countdown(4); // call the recursive function 8 | return 0; 9 | } 10 | 11 | void countdown(int n) 12 | { 13 | using namespace std; 14 | cout << "Counting down ... " << n << endl; 15 | if (n > 0) 16 | countdown(n-1); // function calls itself 17 | cout << n << ":Kaboom!\n"; 18 | } 19 | -------------------------------------------------------------------------------- /ch07/ruler.cpp: -------------------------------------------------------------------------------- 1 | // ruler.cpp -- using recursion to subdivide a ruler 2 | #include 3 | const int Len = 66; 4 | const int Divs = 6; 5 | void subdivide(char ar[], int low, int high, int level); 6 | int main() 7 | { 8 | char ruler[Len]; 9 | int i; 10 | for (i = 1; i < Len - 2; i++) 11 | ruler[i] = ' '; 12 | ruler[Len - 1] = '\0'; 13 | int max = Len - 2; 14 | int min = 0; 15 | ruler[min] = ruler[max] = '|'; 16 | std::cout << ruler << std::endl; 17 | for (i = 1; i <= Divs; i++) 18 | { 19 | subdivide(ruler, min, max, i); 20 | std::cout << ruler << std::endl; 21 | for (int j = 1; j < Len - 2; j++) 22 | ruler[j] = ' '; // reset the blank ruler 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | void subdivide(char ar[], int low, int high, int level) 29 | { 30 | if (level == 0) 31 | return; 32 | int mid = (high + low) / 2; 33 | ar[mid] = '|'; 34 | subdivide(ar, low, mid, level - 1); 35 | subdivide(ar, mid, high, level - 1); 36 | } 37 | -------------------------------------------------------------------------------- /ch07/strgback.cpp: -------------------------------------------------------------------------------- 1 | // strgback.cpp -- a function that returns a pointer to char 2 | #include 3 | char * buildstr(char c, int n); // prototype 4 | int main() 5 | { 6 | using namespace std; 7 | int times; 8 | char ch; 9 | 10 | cout << "Enter a character: "; 11 | cin >> ch; 12 | cout << "Enter an integer: "; 13 | cin >> times; 14 | char * ps = buildstr(ch, times); 15 | cout << ps << endl; 16 | delete [] ps; // free memory 17 | ps = buildstr('+', 20); // reuse pointer 18 | cout << ps << "-DONE-" << ps << endl; 19 | delete [] ps; // free memory 20 | return 0; 21 | } 22 | 23 | // builds string made of n c characters 24 | char * buildstr(char c, int n) 25 | { 26 | char * pstr = new char[n+1]; 27 | pstr[n] = '\0'; // terminate string 28 | while (n-- > 0) 29 | pstr[n] = c; // fill rest of string 30 | return pstr; 31 | } 32 | -------------------------------------------------------------------------------- /ch07/strgfun.cpp: -------------------------------------------------------------------------------- 1 | // strgfun.cpp -- functions with a string argument 2 | #include 3 | unsigned int c_in_str(const char * str, char ch); 4 | int main() 5 | { 6 | using namespace std; 7 | char mmm[15] = "minimum"; // string in an array 8 | // some systems require preceding char with static to 9 | // enable array initialization 10 | 11 | char *wail = "ululate"; 12 | 13 | unsigned int ms = c_in_str(mmm, 'm'); 14 | unsigned int us = c_in_str(wail, 'u'); 15 | cout << ms << " m characters in " << mmm << endl; 16 | cout << us << " u characters in " << wail << endl; 17 | return 0; 18 | } 19 | 20 | // this function counts the number of ch characters 21 | // in the string str 22 | unsigned int c_in_str(const char * str, char ch) 23 | { 24 | unsigned int count = 0; 25 | 26 | while (*str) // quit when *str is '\0' 27 | { 28 | if (*str == ch) 29 | count++; 30 | str++; // move pointer to next char 31 | } 32 | return count; 33 | } 34 | -------------------------------------------------------------------------------- /ch07/topfive.cpp: -------------------------------------------------------------------------------- 1 | // topfive.cpp -- handling an array of string objects 2 | #include 3 | #include 4 | using namespace std; 5 | const int SIZE = 5; 6 | void display(const string sa[], int n); 7 | int main() 8 | { 9 | string list[SIZE]; // an array holding 5 string object 10 | cout << "Enter your " << SIZE << " favorite astronomical sights:\n"; 11 | for (int i = 0; i < SIZE; i++) 12 | { 13 | cout << i + 1 << ": "; 14 | getline(cin, list[i]); 15 | } 16 | 17 | cout << "Your list:\n"; 18 | display(list, SIZE); 19 | 20 | return 0; 21 | } 22 | 23 | void display(const string sa[], int n) 24 | { 25 | for (int i = 0; i < n; i++) 26 | cout << i + 1 << ": " << sa[i] << endl; 27 | } 28 | -------------------------------------------------------------------------------- /ch07/twoarg.cpp: -------------------------------------------------------------------------------- 1 | // twoarg.cpp -- a function with 2 arguments 2 | #include 3 | using namespace std; 4 | void n_chars(char, int); 5 | int main() 6 | { 7 | int times; 8 | char ch; 9 | 10 | cout << "Enter a character: "; 11 | cin >> ch; 12 | while (ch != 'q') // q to quit 13 | { 14 | cout << "Enter an integer: "; 15 | cin >> times; 16 | n_chars(ch, times); // function with two arguments 17 | cout << "\nEnter another character or press the" 18 | " q-key to quit: "; 19 | cin >> ch; 20 | } 21 | cout << "The value of times is " << times << ".\n"; 22 | cout << "Bye\n"; 23 | return 0; 24 | } 25 | 26 | void n_chars(char c, int n) // displays c n times 27 | { 28 | while (n-- > 0) // continue until n reaches 0 29 | cout << c; 30 | } 31 | -------------------------------------------------------------------------------- /ch08/choices.cpp: -------------------------------------------------------------------------------- 1 | // choices.cpp -- choosing a template 2 | #include 3 | 4 | template // or template 5 | T lesser(T a, T b) // #1 6 | { 7 | return a < b ? a : b; 8 | } 9 | 10 | int lesser(int a, int b) // #2 11 | { 12 | a = a < 0 ? -a : a; 13 | b = b < 0 ? -b : b; 14 | return a < b ? a : b; 15 | } 16 | 17 | int main() 18 | { 19 | using namespace std; 20 | int m = 20; 21 | int n = -30; 22 | double x = 15.5; 23 | double y = 25.9; 24 | 25 | cout << lesser(m, n) << endl; // use #2 26 | cout << lesser(x, y) << endl; // use #1 with double 27 | cout << lesser<>(m,n) << endl; // use #1 with int 28 | cout << lesser(x,y) << endl; // use #1 with int 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /ch08/cubes.cpp: -------------------------------------------------------------------------------- 1 | // cubes.cpp -- regular and reference arguments 2 | #include 3 | double cube(double a); 4 | double refcube(double &ra); 5 | int main() 6 | { 7 | using namespace std; 8 | double x = 3.0; 9 | 10 | cout << cube(x); 11 | cout << " = cube of " << x << endl; 12 | cout << refcube(x); 13 | cout << " = cube of " << x << endl; 14 | return 0; 15 | } 16 | 17 | double cube(double a) 18 | { 19 | a *= a * a; 20 | return a; 21 | } 22 | 23 | double refcube(double &ra) 24 | { 25 | ra *= ra * ra; 26 | return ra; 27 | } 28 | -------------------------------------------------------------------------------- /ch08/ep-data.txt: -------------------------------------------------------------------------------- 1 | Focal length of objective: 1800mm 2 | f.l. eyepiece magnification 3 | 30.0 60 4 | 19.0 95 5 | 14.0 129 6 | 8.8 205 7 | 7.5 240 8 | -------------------------------------------------------------------------------- /ch08/firstref.cpp: -------------------------------------------------------------------------------- 1 | // firstref.cpp -- defining and using a reference 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int rats = 101; 7 | int & rodents = rats; // rodents is a reference 8 | cout << "rats = " << rats; 9 | cout << ", rodents = " << rodents << endl; 10 | rodents++; 11 | cout << "rats = " << rats; 12 | cout << ", rodents = " << rodents << endl; 13 | 14 | // some implementations require type casting the following 15 | // addresses to type unsigned 16 | cout << "rats address = " << &rats; 17 | cout << ", rodents address = " << &rodents << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch08/funtemp.cpp: -------------------------------------------------------------------------------- 1 | // functemp.cpp -- using a function templates 2 | #include 3 | // function template prototype 4 | template // or class T 5 | void Swap(T &a, T &b); 6 | 7 | int main() 8 | { 9 | using namespace std; 10 | int i = 10; 11 | int j = 20; 12 | cout << "i, j = " << i << ", " << j << ".\n"; 13 | cout << "Using compiler-generated int swapper:\n"; 14 | Swap(i,j); // generates void Swap(int &, int &) 15 | cout << "Now i, j = " << i << ", " << j << ".\n"; 16 | 17 | double x = 24.5; 18 | double y = 81.7; 19 | cout << "x, y = " << x << ", " << y << ".\n"; 20 | cout << "Using compiler-generated double swapper:\n"; 21 | Swap(x,y); // generate void Swap(double &, double &); 22 | cout << "Now x, y = " << x << ", " << y << ".\n"; 23 | // cin.get(); 24 | return 0; 25 | } 26 | 27 | // function template definition 28 | template // or class T 29 | void Swap(T &a, T &b) 30 | { 31 | T temp; // temp a variable of type T 32 | temp = a; 33 | a = b; 34 | b = temp; 35 | } 36 | -------------------------------------------------------------------------------- /ch08/inline.cpp: -------------------------------------------------------------------------------- 1 | // inline.cpp -- using an inline function 2 | #include 3 | 4 | // an inline function definition 5 | inline double square(double x) {return x * x;} 6 | 7 | int main() 8 | { 9 | using namespace std; 10 | double a, b; 11 | double c = 13.0; 12 | 13 | a = square(5.0); 14 | b = square(4.5 + 7.5); // can pass expressions 15 | cout << "a = " << a << ", b = " << b << "\n"; 16 | cout << "c = " << c; 17 | cout << ", c squared = " << square(c++) << "\n"; 18 | cout << "Now c = " << c << "\n"; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /ch08/left.cpp: -------------------------------------------------------------------------------- 1 | // left.cpp -- string function with a default argument 2 | #include 3 | const int ArSize = 80; 4 | char * left(const char * str, int n = 1); 5 | int main() 6 | { 7 | using namespace std; 8 | char sample[ArSize]; 9 | cout << "Enter a string:\n"; 10 | cin.get(sample, ArSize); 11 | char *ps = left(sample, 4); 12 | cout << ps << endl; 13 | delete [] ps; // free old string 14 | ps = left(sample); 15 | cout << ps << endl; 16 | delete [] ps; // free new string 17 | return 0; 18 | } 19 | 20 | // This function returns a pointer to a new string 21 | // consisting of the first n characters in the str string 22 | char * left(const char * str, int n) 23 | { 24 | if (n < 0) 25 | n = 0; 26 | char *p = new char[n+1]; 27 | int i; 28 | for (i = 0; i < n && str[i]; i++) 29 | p[i] = str[i]; // copy characters 30 | while (i <= n) 31 | p[i++] = '\0'; // set rest of string to '\0' 32 | return p; 33 | } 34 | -------------------------------------------------------------------------------- /ch08/secref.cpp: -------------------------------------------------------------------------------- 1 | // secref.cpp -- defining and using a reference 2 | #include 3 | int main() 4 | { 5 | using namespace std; 6 | int rats = 101; 7 | int & rodents = rats; // rodents is a reference 8 | 9 | cout << "rats = " << rats; 10 | cout << ", rodents = " << rodents << endl; 11 | cout << "rats address = " << &rats; 12 | cout << ", rodents address = " << &rodents << endl; 13 | 14 | int bunnies = 50; 15 | rodents = bunnies; // can we change the reference? 16 | cout << "bunnies = " << bunnies; 17 | cout << ", rats = " << rats; 18 | cout << ", rodents = " << rodents << endl; 19 | 20 | cout << "bunnies address = " << &bunnies; 21 | cout << ", rodents address = " << &rodents << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /ch09/coordin.h: -------------------------------------------------------------------------------- 1 | // coordin.h -- structure template and function prototypes 2 | // structure templates 3 | #ifndef COORDIN_H_ 4 | #define COORDIN_H_ 5 | 6 | struct polar 7 | { 8 | double distance; // distance from origin 9 | double angle; // direction from origin 10 | }; 11 | 12 | struct rect 13 | { 14 | double x; // horizontal distance from origin 15 | double y; // vertical distance from origin 16 | }; 17 | 18 | // prototypes 19 | polar rect_to_polar(rect xypos); 20 | void show_polar(polar dapos); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /ch09/external.cpp: -------------------------------------------------------------------------------- 1 | // external.cpp -- external variables 2 | // compile with support.cpp 3 | #include 4 | using namespace std; 5 | // external variable 6 | double warming = 0.3; // warming defined 7 | // function prototypes 8 | void update(double dt); 9 | void local(); 10 | 11 | int main() // use global variable 12 | { 13 | cout << "Global warming is " << warming << " degrees.\n"; 14 | update(0.1); // call function to change warming 15 | cout << "Global warming is " << warming << " degress.\n"; 16 | local(); // call function with local warming 17 | cout << "Global warming is " << warming << " degrees.\n"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch09/file1.cpp: -------------------------------------------------------------------------------- 1 | // file1.cpp -- example of a three-file program 2 | #include 3 | #include "coordin.h" // structure templates, function prototypes 4 | using namespace std; 5 | int main() 6 | { 7 | rect rplace; 8 | polar pplace; 9 | 10 | cout << "Enter the x and y values: "; 11 | while (cin >> rplace.x >> rplace.y) // slick use of cin 12 | { 13 | pplace = rect_to_polar(rplace); 14 | show_polar(pplace); 15 | cout << "Next two numbers (q to quit): "; 16 | } 17 | cout << "Bye!\n"; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch09/file2.cpp: -------------------------------------------------------------------------------- 1 | // file2.cpp -- contains function called in file1.cpp 2 | #include 3 | #include 4 | #include "coordin.h" // structure templates, function prototypes 5 | 6 | // convert rectangular to polar coordinates 7 | polar rect_to_polar(rect xypos) 8 | { 9 | using namespace std; 10 | polar answer; 11 | 12 | answer.distance = 13 | sqrt( xypos.x * xypos.x + xypos.y + xypos.y); 14 | 15 | answer.angle = atan2(xypos.y, xypos.x); 16 | return answer; // returns a polar structure 17 | } 18 | 19 | // show polar coordinates, converting angle to degrees 20 | void show_polar(polar dapos) 21 | { 22 | using namespace std; 23 | const double Rad_to_deg = 57.29577951; 24 | 25 | cout << "distance = " << dapos.distance; 26 | cout << ", angle = " << dapos.angle * Rad_to_deg; 27 | cout << " degrees\n"; 28 | } 29 | -------------------------------------------------------------------------------- /ch09/namesp.cpp: -------------------------------------------------------------------------------- 1 | // namesp.cpp -- namespaces 2 | #include 3 | #include "namesp.h" 4 | 5 | namespace pers 6 | { 7 | using std::cout; 8 | using std::cin; 9 | void getPerson(Person & rp) 10 | { 11 | cout << "Enter first name: "; 12 | cin >> rp.fname; 13 | cout << "Enter last name: "; 14 | cin >> rp.lname; 15 | } 16 | void showPerson(const Person & rp) 17 | { 18 | std::cout << rp.lname << ", " << rp.fname; 19 | } 20 | } 21 | 22 | namespace debts 23 | { 24 | void getDebt(Debt & rd) 25 | { 26 | getPerson(rd.name); 27 | std::cout << "Enter debt: "; 28 | std::cin >> rd.amount; 29 | } 30 | void showDebt(const Debt & rd) 31 | { 32 | showPerson(rd.name); 33 | std::cout << ": $" << rd.amount << std::endl; 34 | } 35 | double sumDebts(const Debt ar [], int n) 36 | { 37 | double total = 0; 38 | for (int i = 0; i < n; i++) 39 | total += ar[i].amount; 40 | return total; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /ch09/namesp.h: -------------------------------------------------------------------------------- 1 | // namesp.h 2 | #include 3 | // create the pers and debts namespaces 4 | namespace pers 5 | { 6 | struct Person 7 | { 8 | std::string fname; 9 | std::string lname; 10 | }; 11 | void getPerson(Person &); 12 | void showPerson(const Person &); 13 | } 14 | 15 | namespace debts 16 | { 17 | using namespace pers; 18 | struct Debt 19 | { 20 | Person name; 21 | double amount; 22 | }; 23 | void getDebt(Debt &); 24 | void showDebt(const Debt &); 25 | double sumDebts(const Debt ar[], int n); 26 | } 27 | -------------------------------------------------------------------------------- /ch09/support.cpp: -------------------------------------------------------------------------------- 1 | // support.cpp -- use external variable 2 | // compile with external.cpp 3 | #include 4 | extern double warming; // use warming from another file 5 | 6 | // function prototypes 7 | void update(double dt); 8 | void local(); 9 | 10 | using std::cout; 11 | void update(double dt) // modified global variable 12 | { 13 | extern double warming; // optional redeclaration 14 | warming += dt; // uses global warming 15 | cout << "Updating global warming to " << warming; 16 | cout << " degrees.\n"; 17 | } 18 | 19 | void local() // use local variable 20 | { 21 | double warming = 0.8; // new variable hides external one 22 | 23 | cout << "Local warming = " << warming << " degrees.\n"; 24 | // Access global variable with the 25 | // scope resolution operator 26 | cout << "But global warming = " << ::warming; 27 | cout << " degrees.\n"; 28 | } 29 | -------------------------------------------------------------------------------- /ch09/twofile1.cpp: -------------------------------------------------------------------------------- 1 | // twofile1.cpp -- variable with external and internal 2 | #include // to be compiled with twofile2.cpp 3 | int tom = 3; // external variable definition 4 | int dick = 30; // external variable definition 5 | static int harry = 300; // static, internal linkage 6 | 7 | // function prototype 8 | void remote_access(); 9 | 10 | int main() 11 | { 12 | using namespace std; 13 | cout << "main() reports the following addresses:\n"; 14 | cout << &tom << " = &tom, " << &dick << " = &dick, "; 15 | cout << &harry << " = &harry\n"; 16 | remote_access(); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /ch09/twofile2.cpp: -------------------------------------------------------------------------------- 1 | // twofile2.cpp -- variables with internal and external linkage 2 | #include 3 | extern int tom; // tom defined elsewhere 4 | static int dick = 10; // overrides external dick 5 | int harry = 200; // external variable definition, 6 | // no confilict with twofile1 harry 7 | 8 | void remote_access() 9 | { 10 | using namespace std; 11 | cout << "remote_access() reports the following addresses:\n"; 12 | cout << &tom << " = &tom, " << &dick << " = &dick, "; 13 | cout << &harry << " = &harry\n"; 14 | } 15 | -------------------------------------------------------------------------------- /ch09/usenmsp.cpp: -------------------------------------------------------------------------------- 1 | // usenmsp.cpp -- using namespaces 2 | #include 3 | #include "namesp.h" 4 | void other(void); 5 | void another(void); 6 | int main(void) 7 | { 8 | using debts::Debt; 9 | 10 | using debts::showDebt; 11 | Debt golf = { {"Benny", "Goatsniff"}, 120.0 }; 12 | showDebt(golf); 13 | other(); 14 | another(); 15 | return 0; 16 | } 17 | 18 | void other(void) 19 | { 20 | using std::cout; 21 | using std::endl; 22 | using namespace debts; 23 | Person dg = {"Doodles", "Glister"}; 24 | showPerson(dg); 25 | cout << endl; 26 | Debt zippy[3]; 27 | int i; 28 | for (i = 0; i < 3; i++) 29 | getDebt(zippy[i]); 30 | 31 | for (i = 0; i < 3; i++) 32 | showDebt(zippy[i]); 33 | cout << "Total debt: $" << sumDebts(zippy, 3) << endl; 34 | return; 35 | } 36 | 37 | void another(void) 38 | { 39 | using pers::Person; 40 | Person collector = {"Milo", "Rightshift"}; 41 | pers::showPerson(collector); 42 | std::cout << std::endl; 43 | } 44 | -------------------------------------------------------------------------------- /ch10/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all 2 | all : stacker stock00 stock10 stock20 3 | stacker: stacker.o stack.o 4 | g++ -o stacker stacker.o stack.o 5 | stock00: stock00.o usestock0.o 6 | g++ -o stock00 stock00.o usestock0.o 7 | stock10: stock10.o usestock1.o 8 | g++ -o stock10 stock10.o usestock1.o 9 | stock20: stock20.o usestock2.o 10 | g++ -o stock20 stock20.o usestock2.o 11 | 12 | stack.o: stack.cpp stack.h 13 | g++ -c stack.cpp 14 | stacker.o: stacker.cpp stack.h 15 | g++ -c stacker.cpp 16 | stock00.o: stock00.cpp stock00.h 17 | g++ -c stock00.cpp 18 | stock10.o: stock10.cpp stock10.h 19 | g++ -c stock10.cpp 20 | stock20.o: stock20.cpp stock20.h 21 | g++ -c stock20.cpp 22 | usestock0.o: usestock0.cpp stock00.h 23 | g++ -c usestock0.cpp 24 | usestock1.o: usestock1.cpp stock10.h 25 | g++ -c usestock1.cpp 26 | usestock2.o: usestock2.cpp stock20.h 27 | g++ -c usestock2.cpp 28 | .PHONY: cleanobj 29 | cleanobj: 30 | rm -f *.o 31 | 32 | .PHONY: clean 33 | clean: 34 | find . -maxdepth 1 -type f -perm /111 -exec rm {} \; 35 | rm -f *.o 36 | -------------------------------------------------------------------------------- /ch10/stack.cpp: -------------------------------------------------------------------------------- 1 | // stack.cpp -- Stack member functions 2 | #include "stack.h" 3 | Stack::Stack() // create an empty stack 4 | { 5 | top = 0; 6 | } 7 | 8 | bool Stack::isempty() const 9 | { 10 | return top == 0; 11 | } 12 | 13 | bool Stack::isfull() const 14 | { 15 | return top == MAX; 16 | } 17 | 18 | bool Stack::push(const Item & item) 19 | { 20 | if (top < MAX) 21 | { 22 | items[top++] = item; 23 | return true; 24 | } 25 | else 26 | return false; 27 | } 28 | 29 | bool Stack::pop(Item & item) 30 | { 31 | if (top > 0) 32 | { 33 | item = items[--top]; 34 | return true; 35 | } 36 | else 37 | return false; 38 | } 39 | -------------------------------------------------------------------------------- /ch10/stack.h: -------------------------------------------------------------------------------- 1 | // stack.h -- class definition for the stack ADT 2 | #ifndef STACK_H_ 3 | #define STACK_H_ 4 | 5 | typedef unsigned long Item; 6 | 7 | class Stack 8 | { 9 | private: 10 | enum {MAX = 10}; // constant specific to class 11 | Item items[MAX]; // holds stack items 12 | int top; // index for top stack item 13 | public: 14 | Stack(); 15 | bool isempty() const; 16 | bool isfull() const; 17 | // push() returns false if stack already is full, true otherwise 18 | bool push(const Item & item); // add item to stack 19 | // pop() returns false if stack already is empty, true otherwise 20 | bool pop(Item & item); // pop top into item 21 | }; 22 | #endif 23 | -------------------------------------------------------------------------------- /ch10/stock00.h: -------------------------------------------------------------------------------- 1 | // stock00.h -- Stock class interface 2 | // version 00 3 | #ifndef STOCK00_H_ 4 | #define STOCK00_H_ 5 | 6 | #include 7 | 8 | class Stock // class declaration 9 | { 10 | private: 11 | std::string company; 12 | long shares; 13 | double share_val; 14 | double total_val; 15 | void set_tot() { total_val = shares * share_val; } 16 | public: 17 | void acquire(const std::string & co, long n, double pr); 18 | void buy(long num, double price); 19 | void sell(long num, double price); 20 | void update(double price); 21 | void show(); 22 | }; // note semicolon at the end 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /ch10/stock10.h: -------------------------------------------------------------------------------- 1 | // stock10.h -- Stock class declaration with constructors, destructor added 2 | #ifndef STOCK10_H_ 3 | #define STOCK10_H_ 4 | #include 5 | 6 | class Stock 7 | { 8 | private: 9 | std::string company; 10 | long shares; 11 | double share_val; 12 | double total_val; 13 | void set_tot() { total_val = shares * share_val; } 14 | public: 15 | // two constructors 16 | Stock(); // default constructor 17 | Stock(const std::string & co, long n = 0, double pr = 0.0); 18 | ~Stock(); // noisy destructor 19 | void buy(long num, double price); 20 | void sell(long num, double price); 21 | void update(double price); 22 | void show(); 23 | }; 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /ch10/stock20.h: -------------------------------------------------------------------------------- 1 | // stock20,h -- augmented version 2 | #ifndef STOCK20_H_ 3 | #define STOCK20_H_ 4 | #include 5 | 6 | class Stock 7 | { 8 | private: 9 | std::string company; 10 | int shares; 11 | double share_val; 12 | double total_val; 13 | void set_tot() { total_val = shares * share_val; } 14 | public: 15 | Stock(); // default constructor 16 | Stock(const std::string & co, long n = 0, double pr = 0.0); 17 | ~Stock(); // do-nothing destructor 18 | void buy(long num, double price); 19 | void sell(long num, double price); 20 | void update(double price); 21 | void show() const; 22 | const Stock & topval(const Stock & s) const; 23 | }; 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /ch10/stuff: -------------------------------------------------------------------------------- 1 | I am a Unix file. I am proud 2 | to be a Unix file. 3 | -------------------------------------------------------------------------------- /ch10/usestock0.cpp: -------------------------------------------------------------------------------- 1 | // usestck0.cpp -- the client program 2 | // complile with stock00.cpp 3 | #include 4 | #include "stock00.h" 5 | int main() 6 | { 7 | Stock fluffy_the_cat; 8 | fluffy_the_cat.acquire("NanoSmart", 20, 12.50); 9 | fluffy_the_cat.show(); 10 | fluffy_the_cat.buy(15, 18.125); 11 | fluffy_the_cat.show(); 12 | fluffy_the_cat.sell(400, 20.00); 13 | fluffy_the_cat.show(); 14 | fluffy_the_cat.buy(300000,40.125); 15 | fluffy_the_cat.show(); 16 | fluffy_the_cat.sell(300000,0.125); 17 | fluffy_the_cat.show(); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /ch10/usestock1.cpp: -------------------------------------------------------------------------------- 1 | // usestock1.cpp -- using the Stock class 2 | // compile with stock10.cpp 3 | #include 4 | #include "stock10.h" 5 | 6 | int main() 7 | { 8 | { 9 | using std::cout; 10 | cout << "Using constructors to create new objects\n"; 11 | Stock stock1("NanoSmart", 12, 20.0); // syntax 1 12 | stock1.show(); 13 | Stock stock2 = Stock("Boffo Objects", 2, 2.0); // syntax 2 14 | stock2.show(); 15 | 16 | cout << "Assigning stock1 to stock2:\n"; 17 | stock2 = stock1; 18 | cout << "Listing stock1 and stock2:\n"; 19 | stock1.show(); 20 | stock2.show(); 21 | 22 | cout << "Using a constructor to reset an object\n"; 23 | stock1 = Stock("Nifty Foods", 10, 50.0); // temp object 24 | cout << "Revised stock1:\n"; 25 | stock1.show(); 26 | cout << "Done\n"; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /ch10/usestock2.cpp: -------------------------------------------------------------------------------- 1 | // usestock2.cpp -- using the Stock class 2 | // compile with stock20.cpp 3 | #include 4 | #include "stock20.h" 5 | 6 | const int STKS = 4; 7 | int main() 8 | { 9 | // create an array of initialized objects 10 | Stock stocks[STKS] = { 11 | Stock("NanoSmart", 12, 20.0), 12 | Stock("Boffo Objects", 200, 2.0), 13 | Stock("Monolithic Obelisks", 130, 3.25), 14 | Stock("Fleep Enterprises", 60, 6.5) 15 | }; 16 | 17 | std::cout << "Stock holdings:\n"; 18 | int st; 19 | for (st = 0; st < STKS; st++) 20 | stocks[st].show(); 21 | // set pointer to first element 22 | const Stock * top = &stocks[0]; 23 | for (st = 1; st < STKS; st++) 24 | top = &top->topval(stocks[st]); 25 | // now top points to the most valuable holding 26 | std::cout << "\nMost valuable holding:\n"; 27 | top->show(); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /ch11/mytime0.cpp: -------------------------------------------------------------------------------- 1 | // mytime0.cpp -- implementing Time methods 2 | #include 3 | #include "mytime0.h" 4 | 5 | Time::Time() 6 | { 7 | hours = minutes = 0; 8 | } 9 | 10 | Time::Time(int h, int m) 11 | { 12 | hours = h; 13 | minutes = m; 14 | } 15 | 16 | void Time::AddMin(int m) 17 | { 18 | minutes += m; 19 | hours += minutes / 60; 20 | minutes %= 60; 21 | } 22 | 23 | void Time::AddHr(int h) 24 | { 25 | hours += h; 26 | } 27 | 28 | void Time::Reset(int h, int m) 29 | { 30 | hours = h; 31 | minutes = m; 32 | } 33 | 34 | Time Time::Sum(const Time & t) const 35 | { 36 | Time sum; 37 | sum.minutes = minutes + t.minutes; 38 | sum.hours = hours + t.hours + sum.minutes / 60; 39 | sum.minutes %= 60; 40 | return sum; 41 | } 42 | 43 | void Time::Show() const 44 | { 45 | std::cout << hours << " hours, " << minutes << " minutes."; 46 | } 47 | -------------------------------------------------------------------------------- /ch11/mytime0.h: -------------------------------------------------------------------------------- 1 | // mytime0.h -- Time class before operator overloading 2 | #ifndef MYTIME0_H_ 3 | #define MYTIME0_H_ 4 | 5 | class Time 6 | { 7 | private: 8 | int hours; 9 | int minutes; 10 | public: 11 | Time(); 12 | Time(int h, int m = 0); 13 | void AddMin(int m); 14 | void AddHr(int h); 15 | void Reset(int h = 0, int m = 0); 16 | Time Sum(const Time & t) const; 17 | void Show() const; 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /ch11/mytime1.cpp: -------------------------------------------------------------------------------- 1 | // mytime1.cpp -- implementing Time methods 2 | #include 3 | #include "mytime1.h" 4 | 5 | Time::Time() 6 | { 7 | hours = minutes = 0; 8 | } 9 | 10 | Time::Time(int h, int m) 11 | { 12 | hours = h; 13 | minutes = m; 14 | } 15 | 16 | void Time::AddMin(int m) 17 | { 18 | minutes += m; 19 | hours += minutes / 60; 20 | minutes %= 60; 21 | } 22 | 23 | void Time::AddHr(int h) 24 | { 25 | hours += h; 26 | } 27 | 28 | void Time::Reset(int h, int m) 29 | { 30 | hours = h; 31 | minutes = m; 32 | } 33 | 34 | Time Time::operator+(const Time & t) const 35 | { 36 | Time sum; 37 | sum.minutes = minutes + t.minutes; 38 | sum.hours = hours + t.hours + sum.minutes / 60; 39 | sum.minutes %= 60; 40 | return sum; 41 | } 42 | 43 | void Time::Show() const 44 | { 45 | std::cout << hours << " hours, " << minutes << " minutes"; 46 | } 47 | -------------------------------------------------------------------------------- /ch11/mytime1.h: -------------------------------------------------------------------------------- 1 | // mytime1.h -- Time class before operator overloading 2 | #ifndef MYTIME1_H_ 3 | #define MYTIME1_H_ 4 | 5 | class Time 6 | { 7 | private: 8 | int hours; 9 | int minutes; 10 | public: 11 | Time(); 12 | Time(int h, int m = 0); 13 | void AddMin(int m); 14 | void AddHr(int h); 15 | void Reset(int h = 0, int m = 0); 16 | Time operator+(const Time & t) const; 17 | void Show() const; 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /ch11/mytime2.h: -------------------------------------------------------------------------------- 1 | // mytime2.h -- Time class after operator overloading 2 | #ifndef MYTIME2_H_ 3 | #define MYTIME2_H_ 4 | 5 | class Time 6 | { 7 | private: 8 | int hours; 9 | int minutes; 10 | public: 11 | Time(); 12 | Time(int h, int m = 0); 13 | void AddMin(int m); 14 | void AddHr(int h); 15 | void Reset(int h = 0, int m = 0); 16 | Time operator+(const Time & t) const; 17 | Time operator-(const Time & t) const; 18 | Time operator*(double n) const; 19 | void Show() const; 20 | }; 21 | #endif 22 | -------------------------------------------------------------------------------- /ch11/mytime3.h: -------------------------------------------------------------------------------- 1 | // mytime3.h -- Time class with friends 2 | #ifndef MYTIME3_H_ 3 | #define MYTIME3_H_ 4 | #include 5 | 6 | class Time 7 | { 8 | private: 9 | int hours; 10 | int minutes; 11 | public: 12 | Time(); 13 | Time(int h, int m = 0); 14 | void AddMin(int m); 15 | void AddHr(int h); 16 | void Reset(int h = 0, int m = 0); 17 | Time operator+(const Time & t) const; 18 | Time operator-(const Time & t) const; 19 | Time operator*(double n) const; 20 | friend Time operator*(double m, const Time & t) 21 | { return t * m; } // inline definition 22 | friend std::ostream & operator<<(std::ostream & os, const Time & t); 23 | }; 24 | #endif 25 | -------------------------------------------------------------------------------- /ch11/stone1.cpp: -------------------------------------------------------------------------------- 1 | // stone1.cpp -- user-defined conversion functions 2 | // compile with stonewt1.cpp 3 | #include 4 | #include "stonewt1.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | Stonewt poppins(9,2.8); // 9 stone, 2.8 pounds 10 | double p_wt = poppins; // implicit conversion 11 | cout << "Convert to double => "; 12 | cout << "Poppins: " << p_wt << " pounds.\n"; 13 | cout << "Convert to int => "; 14 | cout << "Poppins: " << int (poppins) << " pounds.\n"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /ch11/stonewt.cpp: -------------------------------------------------------------------------------- 1 | // stonewt.cpp -- Stonewt methods 2 | #include 3 | using std::cout; 4 | #include "stonewt.h" 5 | 6 | // construct Stonewt object from double value 7 | Stonewt::Stonewt(double lbs) 8 | { 9 | stone = int (lbs) / Lbs_per_stn; // integer division 10 | pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs); 11 | pounds = lbs; 12 | } 13 | 14 | // construct Stonewt object from stone, double values 15 | Stonewt::Stonewt(int stn, double lbs) 16 | { 17 | stone = stn; 18 | pds_left = lbs; 19 | pounds = stn * Lbs_per_stn + lbs; 20 | } 21 | 22 | Stonewt::Stonewt() // default constructor, wt = 0 23 | { 24 | stone = pounds = pds_left = 0; 25 | } 26 | 27 | Stonewt::~Stonewt() // destructor 28 | { 29 | } 30 | 31 | // show weight in stones 32 | void Stonewt::show_stn() const 33 | { 34 | cout << stone << " stone, " << pds_left << " pounds\n"; 35 | } 36 | 37 | // show weight in pounds 38 | void Stonewt::show_lbs() const 39 | { 40 | cout << pounds << " pounds\n"; 41 | } 42 | -------------------------------------------------------------------------------- /ch11/stonewt.h: -------------------------------------------------------------------------------- 1 | // stonewt.h -- definition for the Stonewt class 2 | #ifndef STONEWT_H_ 3 | #define STONEWT_H_ 4 | class Stonewt 5 | { 6 | private: 7 | enum {Lbs_per_stn = 14}; // pounds per stone 8 | int stone; // whole stones 9 | double pds_left; // fractional pounds 10 | double pounds; // entire weight in pounds 11 | public: 12 | Stonewt(double lbs); // constructor for double pounds 13 | Stonewt(int stn, double lbs); // constructor for stone, lbs 14 | Stonewt(); // default constructor 15 | ~Stonewt(); 16 | void show_lbs() const; // show weight in pounds format 17 | void show_stn() const; // show weight in stone format 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /ch11/stonewt1.h: -------------------------------------------------------------------------------- 1 | // stonewt1.h -- revised definition for the Stonewt class 2 | #ifndef STONEWT1_H_ 3 | #define STONEWT1_H_ 4 | class Stonewt 5 | { 6 | private: 7 | enum {Lbs_per_stn = 14}; // pounds per stone 8 | int stone; // whole stones 9 | double pds_left; // fractional pounds 10 | double pounds; // entire weight in pounds 11 | public: 12 | Stonewt(double lbs); // construct from double pounds 13 | Stonewt(int stn, double lbs); // construct from stone, lbs 14 | Stonewt(); // default constructor 15 | ~Stonewt(); 16 | void show_lbs() const; // show weight in pounds format 17 | void show_stn() const; // show weight in stone format 18 | // conversion functions 19 | operator int() const; 20 | operator double() const; 21 | }; 22 | #endif 23 | -------------------------------------------------------------------------------- /ch11/usetime0.cpp: -------------------------------------------------------------------------------- 1 | // usetime0.cpp -- using the first draft of the Time class 2 | // compile usetime0.cpp and mytime0.cpp together 3 | #include 4 | #include "mytime0.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | Time planning; 11 | Time coding(2, 40); 12 | Time fixing(5, 55); 13 | Time total; 14 | 15 | cout << "planning time = "; 16 | planning.Show(); 17 | cout << endl; 18 | 19 | cout << "coding time = "; 20 | coding.Show(); 21 | cout << endl; 22 | 23 | cout << "fixing time = "; 24 | fixing.Show(); 25 | cout << endl; 26 | 27 | total = coding.Sum(fixing); 28 | cout << "coding.Sum(fixing) = "; 29 | total.Show(); 30 | cout << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /ch11/usetime1.cpp: -------------------------------------------------------------------------------- 1 | // usetime1.cpp -- using the second draft of the Time class 2 | // compile usetime1.cpp and mytime1.cpp together 3 | #include 4 | #include "mytime1.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | Time planning; 11 | Time coding(2, 40); 12 | Time fixing(5, 55); 13 | Time total; 14 | 15 | cout << "planning time = "; 16 | planning.Show(); 17 | cout << endl; 18 | 19 | cout << "coding time = "; 20 | coding.Show(); 21 | cout << endl; 22 | 23 | total = coding + fixing; 24 | // operator notation 25 | cout << "coding + fixing = "; 26 | total.Show(); 27 | cout << endl; 28 | 29 | Time morefixing(3, 28); 30 | cout << "more fixing time = "; 31 | morefixing.Show(); 32 | cout << endl; 33 | total = morefixing.operator+(total); 34 | // function notation 35 | cout << "morefixing.operator+(total) = "; 36 | total.Show(); 37 | cout << endl; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /ch11/usetime2.cpp: -------------------------------------------------------------------------------- 1 | // usetime2.cpp -- using the third draft of the Time class 2 | // compile usetime2.cpp and mytime2.cpp together 3 | #include 4 | #include "mytime2.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | Time weeding(4, 35); 11 | Time waxing(2, 47); 12 | Time total; 13 | Time diff; 14 | Time adjusted; 15 | 16 | cout << "weeding time = "; 17 | weeding.Show(); 18 | cout << endl; 19 | 20 | cout << "waxing time = "; 21 | waxing.Show(); 22 | cout << endl; 23 | 24 | cout << "total work time = "; 25 | total = weeding + waxing; // use operator+() 26 | total.Show(); 27 | cout << endl; 28 | 29 | diff = weeding - waxing; // use operator-() 30 | cout << "weeding time - waxing time = "; 31 | diff.Show(); 32 | cout << endl; 33 | 34 | adjusted = total * 1.5; // use operator*() 35 | cout << "adjusted work time = "; 36 | adjusted.Show(); 37 | cout << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /ch11/usetime3.cpp: -------------------------------------------------------------------------------- 1 | // usetime3.cpp -- using the fourth draft of the Time class 2 | // complile usetime3.cpp and mytime3.cpp together 3 | #include 4 | #include "mytime3.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | Time aida(3, 35); 11 | Time tosca(2, 48); 12 | Time temp; 13 | 14 | cout << "Aida and Tosca:\n"; 15 | cout << aida << "; " << tosca << endl; 16 | temp = aida + tosca; // operator+() 17 | cout << "Aida + Tosca: " << temp << endl; 18 | temp = aida * 1.17; // member operator*() 19 | cout << "Aida * 1.17: " << temp << endl; 20 | cout << "10.0 * Tosca: " << 10.0 * tosca << endl; 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /ch12/strngbad.h: -------------------------------------------------------------------------------- 1 | // strngbad.h -- flawed string class definition 2 | #include 3 | #ifndef STRNGBAD_H_ 4 | #define STRNGBAD_H_ 5 | class StringBad 6 | { 7 | private: 8 | char * str; // pointer to string 9 | int len; // length of string 10 | static int num_strings; // number of objects 11 | public: 12 | StringBad(const char * s); // constructor 13 | StringBad(); // default constructor 14 | ~StringBad(); // destructor 15 | // friend function 16 | friend std::ostream & operator<<(std::ostream & os, 17 | const StringBad & st); 18 | }; 19 | #endif 20 | -------------------------------------------------------------------------------- /ch13/tabtenn0.cpp: -------------------------------------------------------------------------------- 1 | // tabtenn0.cpp -- simple base-class methods 2 | #include "tabtenn0.h" 3 | #include 4 | 5 | TableTennisPlayer::TableTennisPlayer (const string & fn, 6 | const string & ln, bool ht) : firstname(fn), 7 | lastname(ln), hasTable(ht) {} 8 | 9 | void TableTennisPlayer::Name() const 10 | { 11 | std::cout << lastname << ", " << firstname; 12 | } 13 | -------------------------------------------------------------------------------- /ch13/tabtenn0.h: -------------------------------------------------------------------------------- 1 | // tabtenn0.h -- a table tennis base class 2 | #ifndef TABTENN0_H_ 3 | #define TABTENN0_H_ 4 | #include 5 | using std::string; 6 | // simple base class 7 | class TableTennisPlayer 8 | { 9 | private: 10 | string firstname; 11 | string lastname; 12 | bool hasTable; 13 | public: 14 | TableTennisPlayer (const string & fn = "none", 15 | const string & ln = "none", bool ht = false); 16 | void Name() const; 17 | bool HasTable() const { return hasTable; }; 18 | void ResetTable(bool v) { hasTable = v; }; 19 | }; 20 | #endif 21 | -------------------------------------------------------------------------------- /ch13/tabtenn1.cpp: -------------------------------------------------------------------------------- 1 | // tabtenn1.cpp -- simple base-class methods 2 | #include "tabtenn1.h" 3 | #include 4 | 5 | TableTennisPlayer::TableTennisPlayer (const string & fn, 6 | const string & ln, bool ht) : firstname(fn), 7 | lastname(ln), hasTable(ht) {} 8 | 9 | void TableTennisPlayer::Name() const 10 | { 11 | std::cout << lastname << ", " << firstname; 12 | } 13 | 14 | // RatedPlayer methods 15 | RatedPlayer::RatedPlayer(unsigned int r, const string & fn, 16 | const string & ln, bool ht) : TableTennisPlayer(fn, ln, ht) 17 | { 18 | rating = r; 19 | } 20 | 21 | RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer & tp) 22 | : TableTennisPlayer(tp), rating(r) 23 | { 24 | } 25 | -------------------------------------------------------------------------------- /ch13/usebrass1.cpp: -------------------------------------------------------------------------------- 1 | // usebrass1.cpp -- testing bank account classes 2 | // compile with brass.cpp 3 | #include 4 | #include "brass.h" 5 | 6 | int main() 7 | { 8 | using std::cout; 9 | using std::endl; 10 | 11 | Brass Piggy("Porcelot Pigg", 381299, 4000.00); 12 | BrassPlus Hoggy("Horatio Hogg", 382288, 3000.00); 13 | Piggy.ViewAcct(); 14 | cout << endl; 15 | Hoggy.ViewAcct(); 16 | cout << endl; 17 | cout << "Depositing $1000 into the Hogg Account:\n"; 18 | Hoggy.Deposit(1000.00); 19 | cout << "New balance: $" << Hoggy.Balance() << endl; 20 | cout << "Withdrawing $4200 from the Pigg Account:\n"; 21 | Piggy.Withdraw(4200.00); 22 | cout << "Pigg account balance: $" << Piggy.Balance() << endl; 23 | cout << "Withdrawing $4200 from the Hogg Account:\n"; 24 | Hoggy.Withdraw(4200.00); 25 | Hoggy.ViewAcct(); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /ch13/usedma.cpp: -------------------------------------------------------------------------------- 1 | // usedma.cpp -- inheritance, friends and DMA 2 | // compile with dma.cpp 3 | #include 4 | #include "dma.h" 5 | int main() 6 | { 7 | using std::cout; 8 | using std::endl; 9 | 10 | baseDMA shirt("Portabelly", 8); 11 | lacksDMA ballon("red", "Blimpo", 4); 12 | hasDMA map("Mercator", "Buffalo Keys", 5); 13 | cout << "Displaying baseDMA object:\n"; 14 | cout << shirt << endl; 15 | cout << "Displaying lacksDMA object:\n"; 16 | cout << ballon << endl; 17 | cout << "Displaying hasDMA object:\n"; 18 | cout << map << endl; 19 | lacksDMA ballon2(ballon); 20 | cout << "Result of lacksDMA copy:\n"; 21 | cout << ballon2 << endl; 22 | hasDMA map2; 23 | map2 = map; 24 | cout << "Result of hasDMA assignment:\n"; 25 | cout << map2 << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /ch13/usett0.cpp: -------------------------------------------------------------------------------- 1 | // usett0.cpp -- using a base class 2 | #include 3 | #include "tabtenn0.h" 4 | 5 | int main( void ) 6 | { 7 | using std::cout; 8 | TableTennisPlayer player1("Chunk", "Blizzard", true); 9 | TableTennisPlayer player2("Tara", "Boomdea", false); 10 | player1.Name(); 11 | if (player1.HasTable()) 12 | cout << ": has a table.\n"; 13 | else 14 | cout << ": hasn't a table.\n"; 15 | player2.Name(); 16 | if (player2.HasTable()) 17 | cout << ": has a table"; 18 | else 19 | cout << ": hasn't a table.\n"; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ch13/usett1.cpp: -------------------------------------------------------------------------------- 1 | // usett1.cpp -- using base class and derived class 2 | #include 3 | #include "tabtenn1.h" 4 | 5 | int main ( void ) 6 | { 7 | using std::cout; 8 | using std::endl; 9 | TableTennisPlayer player1("Tara", "Boomdea", false); 10 | RatedPlayer rplayer1(1140, "Mallory", "Duck", true); 11 | rplayer1.Name(); // derived object uses base method 12 | if (rplayer1.HasTable()) 13 | cout << ": has a table.\n"; 14 | else 15 | cout << ": hasn't a table.\n"; 16 | player1.Name(); // base object uses base method 17 | if (player1.HasTable()) 18 | cout << ": has a table"; 19 | else 20 | cout << ": hasn't a table.\n"; 21 | cout << "Name: "; 22 | rplayer1.Name(); 23 | cout << "; Rating: " << rplayer1.Rating() << endl; 24 | // initialize RatedPlayer using TableTennisPlayer object 25 | RatedPlayer rplayer2(1212, player1); 26 | cout << "Name: "; 27 | rplayer2.Name(); 28 | cout << "; Rating: " << rplayer2.Rating() << endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /ch14/manyfrnd.cpp: -------------------------------------------------------------------------------- 1 | // manyfrnd.cpp -- unbound template friend to a template class 2 | #include 3 | using std::cout; 4 | using std::endl; 5 | 6 | template 7 | class ManyFriend 8 | { 9 | private: 10 | T item; 11 | public: 12 | ManyFriend(const T & i) : item(i) {} 13 | template friend void show2(C &, D &); 14 | }; 15 | 16 | template void show2(C & c, D & d) 17 | { 18 | cout << c.item << ", " << d.item << endl; 19 | } 20 | 21 | int main() 22 | { 23 | ManyFriend hfi1(10); 24 | ManyFriend hfi2(20); 25 | ManyFriend hfdb(10.5); 26 | cout << "hfi1, hfi2: "; 27 | show2(hfi1, hfi2); 28 | cout << "hfdb, hfi2: "; 29 | show2(hfdb, hfi2); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /ch14/tempparm.cpp: -------------------------------------------------------------------------------- 1 | // tempparm.cpp -- templates as parameters 2 | #include 3 | #include "stacktp.h" 4 | 5 | template