Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Solutions Ior Programming Exercises in C Primer Plus, 5

th
Edition
SP 1 oI 65 September 2, 2004
Chapter 2
//pe2-2.cpp
#include<iostream>
intmain(void)
{
usingnamespacestd;
cout<<"Enteradistanceinfurlongs:";
doublefurlongs;
cin>>furlongs;
doublefeet;
feet=220*furlongs;
cout<<furlongs<<"furlongs="
<<feet<<"feet\n";
return0;
}
//pe2-3.cpp
#include<iostream>
usingnamespacestd;
voidmice();
voidrun();
intmain()
{
mice();
mice();
run();
run();
return0;
}
voidmice()
{
cout<<"Threeblindmice\n";
}
voidrun()
{
cout<<"Seehowtheyrun\n";
}
//pe2-4.cpp
#include<iostream>
doubleC_to_F(double);
intmain()
{
usingnamespacestd;
cout<<"EnteratemperatureinCelsius:";
doubleC;
cin>>C;
doubleF;
F=C_to_F(C);
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 2 oI 65 September 2, 2004
cout<<C<<"degreesCelsius="
<<F<<"degreesFahrenheit\n";
return0;
}
doubleC_to_F(doubletemp)
{
return1.8*temp+32.0;
}
Chapter 3
//pe3-1.cpp
#include<iostream>
constintInch_Per_Foot=12;
intmain(void)
{
usingnamespacestd;
//Note:someenvironmentsdon'tsupportthebackspacecharacter
cout<<"Pleaseenteryourheightininches:___/b/b/b";
intht_inch;
cin>>ht_inch;
intht_feet=ht_inch/Inch_Per_Foot;
intrm_inch=ht_inch%Inch_Per_Foot;
cout<<"Yourheightis"<<ht_feet<<"feet,";
cout<<rm_inch<<"inch(es).\n";
return0;
}
//pe3-3.cpp
#include<iostream>
constdoubleMINS_PER_DEG=60.0;
constdoubleSECS_PER_MIN=60.0;
intmain()
{
usingnamespacestd;
intdegrees;
intminutes;
intseconds;
doublelatitude;
cout<<"Enteralatitudeindegrees,minutes,andseconds:\n";
cout<<"First,enterthedegrees:";
cin>>degrees;
cout<<"Next,entertheminutesofarc:";
cin>>minutes;
cout<<"Finally,enterthesecondsofarc:";
cin>>seconds;
latitude=degrees+(minutes+seconds/SECS_PER_MIN)/MINS_PER_DEG;
cout<<degrees<<"degrees,"<<minutes<<"minutes,"
<<seconds<<"seconds="<<latitude<<"degrees\n";
return0;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 3 oI 65 September 2, 2004
//pe3-5.cpp
#include<iostream>
intmain(void)
{
usingnamespacestd;
cout<<"Howmanymileshaveyoudrivenyourcar?";
floatmiles;
cin>>miles;
cout<<"Howmanygallonsofgasolinedidthecaruse?";
floatgallons;
cin>>gallons;
cout<<"Yourcargot"<<miles/gallons;
cout<<"milespergallon.\n";
return0;
}
//pe3-6.cpp
#include<iostream>
constdoubleKM100_TO_MILES=62.14;
constdoubleLITERS_PER_GALLON=3.875;
intmain(void)
{
usingnamespacestd;
doubleeuro_rating;
doubleus_rating;
cout<<"Enterfuelconsumptioninlitersper100km:";
cin>>euro_rating;
//dividebyLITER_PER_GALLONtogetgallonsper100-km
//dividebyKM100_TO_MILEStogetgallonspermile
//invertresulttogetmilespergallon
us_rating=(LITERS_PER_GALLON*KM100_TO_MILES)/euro_rating;
cout<<euro_rating<<"litersper100kmis";
cout<<us_rating<<"milespergallon.\n";
return0;
}
Chapter 4
//pe4-2.cpp--storingstringsinstringobjects
#include<iostream>
#include<string>
intmain()
{
usingnamespacestd;
stringname;
stringdessert;
cout<<"Enteryourname:\n";
getline(cin,name);//readsthroughnewline
cout<<"Enteryourfavoritedessert:\n";
getline(cin,dessert);
cout<<"Ihavesomedelicious"<<dessert;
cout<<"foryou,"<<name<<".\n";
return0;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 4 oI 65 September 2, 2004
//pe4-3.cpp--storingstringsinchararrays
#include<iostream>
#include<cstring>
constintSIZE=20;
intmain()
{
usingnamespacestd;
charfirstName[SIZE];
charlastName[SIZE];
charfullName[2*SIZE+1];
cout<<"Enteryourfirstname:";
cin>>firstName;
cout<<"Enteryourlastname:";
cin>>lastName;
strncpy(fullName,lastName,SIZE);
strcat(fullName,",");
strncat(fullName,firstName,SIZE);
fullName[SIZE-1]='\0';
cout<<"Here'stheinformationinasinglestring:"
<<fullName<<endl;
return0;
}
//pe4-5.cpp
//acandybarstructure
structCandyBar{
charbrand[40];
doubleweight;
intcalories;
};
#include<iostream>
intmain()
{
usingnamespacestd;//introducesnamespacestd
CandyBarsnack={"MochaMunch",2.3,350};
cout<<"Brandname:"<<snack.brand<<endl;
cout<<"Weight:"<<snack.weight<<endl;
cout<<"Calories:"<<snack.calories<<endl;
return0;
}
//pe4-7.ccp
#include<iostream>
constintSlen=70;
structpizza{
charname[Slen];
floatdiameter;
floatweight;
};
intmain(void)
{
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 5 oI 65 September 2, 2004
usingnamespacestd;
pizzapie;
cout<<"Whatisthenameofthepizzacompany?";
cin.getline(pie.name,Slen);
cout<<"Whatisthediameterofthepizzaininches?";
cin>>pie.diameter;
cout<<"Howmuchdoesthepizzaweighinounces?";
cin>>pie.weight;
cout<<"Company:"<<pie.name<<"\n";
cout<<"Diameter:"<<pie.diameter<<"inches\n";
cout<<"Weight:"<<pie.weight<<"ounces\n";
return0;
}
Chapter 5
//pe5-2.cpp
#include<iostream>
intmain(void)
{
usingnamespacestd;
doublesum=0.0;
doublein;
cout<<"Enteranumber(0toterminate):";
cin>>in;
while(in!=0){
sum+=in;
cout<<"Runningtotal="<<sum<<"\n";
cout<<"Enternextnumber(0toterminate):";
cin>>in;
}
cout<<"Bye!\n";
return0;
}
//pe5-4.cpp
//booksales
#include<iostream>
constintMONTHS=12;
constchar*months[MONTHS]={"January","February","March","April",
"May","June","July","August","September",
"October","November","December"};
intmain()
{
usingnamespacestd;//introducesnamespacestd
intsales[MONTHS];
intmonth;
cout<<"Enterthemonthlysalesfor\"C++forFools\":\n";
for(month=0;month<MONTHS;month++)
{
cout<<"Salesfor"<<months[month]<<":";
cin>>sales[month];
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 6 oI 65 September 2, 2004
doubletotal=0.0;
for(month=0;month<MONTHS;month++)
total+=sales[month];
cout<<"Totalsales:"<<total<<endl;
return0;
}
//pe5-6.cpp
#include<iostream>
structcar{charname[20];intyear;};
intmain(void)
{
usingnamespacestd;
intn;
cout<<"Howmanycarsdoyouwishtocatalog?:";
cin>>n;
while(cin.get()!='\n')//getridofrestofline
;
car*pc=newcar[n];
inti;
for(i=0;i<n;i++)
{
cout<<"Car#"<<(i+1)<<":\n";
cout<<"Pleaseenterthemake:";
cin.getline(pc[i].name,20);
cout<<"Pleaseentertheyearmade:";
cin>>pc[i].year;
while(cin.get()!='\n')//getridofrestofline
;
}
cout<<"Hereisyourcollection:\n";
for(i=0;i<n;i++)
cout<<pc[i].year<<""<<pc[i].name<<"\n";
delete[]pc;
return0;
}
//pe5-7.cpp--countwordsusingC-stylestring
#include<iostream>
#include<cstring>//prototypeforstrcmp()
constintSTR_LIM=50;
intmain()
{
usingnamespacestd;
charword[STR_LIM];
intcount=0;
cout<<"Enterwords(tostop,typetheworddone):\n";
while(cin>>word&&strcmp("done",word))
++count;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 7 oI 65 September 2, 2004
cout<<"Youenteredatotalof"<<count<<"words.\n";
return0;
}
//pe5-9.cpp
//nestedloops
#include<iostream>
intmain()
{
usingnamespacestd;//introducesnamespacestd
introws;
introw;
intcol;
intperiods;
cout<<"Enternumberofrows:";
cin>>rows;
for(row=1;row<=rows;row++)
{
periods=rows-row;
for(col=1;col<=periods;col++)
cout<<'.';
//colalreadyhascorrectvaluefornextloop
for(;col<=rows;col++)
cout<<'*';
cout<<endl;
}
return0;
}
Chapter 6
//pe6-1.cpp
#include<iostream>
#include<cctype>
intmain()
{
usingnamespacestd;//introducesnamespacestd
charch;
cin.get(ch);
while(ch!='@')
{
if(!isdigit(ch))
{
if(isupper(ch))
ch=tolower(ch);
elseif(islower(ch))
ch=toupper(ch);
cout<<ch;
}
cin.get(ch);
}
return0;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 8 oI 65 September 2, 2004
//pe6-3.cpp
#include<iostream>
intmain(void)
{
usingnamespacestd;
cout<<"Pleaseenteroneofthefollowingchoices:\n";
cout<<"c)carnivorep)pianist\n"
<<"t)treeg)game\n";
charch;
cin>>ch;
while(ch!='c'&&ch!='p'&&ch!='t'&&ch!='g')
{
cout<<"Pleaseenterac,p,t,org:";
cin>>ch;
}
switch(ch)
{
case'c':cout<<"Acatisacarnivore.\n";
break;
case'p':cout<<"RaduLupuisapianist.\n";
break;
case't':cout<<"Amapleisatree.\n";
break;
case'g':cout<<"Golfisagame.\n";
break;
default:cout<<"Theprogramshouldn'tgethere!\n";
}
return0;
}
//pe6-5.cpp
//Neutroniataxation
#include<iostream>
constdoubleLEV1=5000;
constdoubleLEV2=15000;
constdoubleLEV3=35000;
constdoubleRATE1=0.10;
constdoubleRATE2=0.15;
constdoubleRATE3=0.20;
intmain()
{
usingnamespacestd;
doubleincome;
doubletax;
cout<<"Enteryourannualincomeintvarps:";
cin>>income;
if(income<=LEV1)
tax=0;
elseif(income<=LEV2)
tax=(income-LEV1)*RATE1;
elseif(income<=LEV3)
tax=RATE1*(LEV2-LEV1)+RATE2*(income-LEV2);
else
tax=RATE1*(LEV2-LEV1)+RATE2*(LEV3-LEV2)
+RATE3*(income-LEV3);
cout<<"YouoweNeutronia"<<tax<<"tvarpsintaxes.\n";
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 9 oI 65 September 2, 2004
return0;
}
//pe6-7.cpp
#include<iostream>
#include<string>
intmain()
{
usingnamespacestd;
stringword;
charch;
intvowel=0;
intconsonant=0;
intother=0;
cout<<"Enterwords(qtoquit):\n";
cin>>word;
while(word!="q")
{
ch=tolower(word[0]);
if(isalpha(ch))
{
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'
||ch=='u')
vowel++;
else
consonant++;
}
else
other++;
cin>>word;
}
cout<<vowel<<"wordsbeginningwithvowels\n";
cout<<consonant<<"wordsbeginningwithconsonants\n";
cout<<other<<"others\n";
return0;
}
//pe6-8.cpp--countingcharacters
#include<iostream>
#include<fstream>//fileI/Osuppport
#include<cstdlib>//supportforexit()
constintSIZE=60;
intmain()
{
usingnamespacestd;
charfilename[SIZE];
charch;
ifstreaminFile;//objectforhandlingfileinput
cout<<"Enternameofdatafile:";
cin.getline(filename,SIZE);
inFile.open(filename);//associateinFilewithafile
if(!inFile.is_open())//failedtoopenfile
{
cout<<"Couldnotopenthefile"<<filename<<endl;
cout<<"Programterminating.\n";
exit(EXIT_FAILURE);
}
intcount=0;//numberofitemsread
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 10 oI 65 September 2, 2004
inFile>>ch;//getfirstvalue
while(inFile.good())//whileinputgoodandnotatEOF
{
count++;//onemoreitemread
inFile>>ch;//getnextvalue
}
cout<<count<<"charactersin"<<filename<<endl;
inFile.close();//finishedwiththefile
return0;
}
Chapter 7
//pe7-1.cpp--harmonicmean
#include<iostream>
doubleh_mean(doublex,doubley);
intmain(void)
{
usingnamespacestd;
doublex,y;
cout<<"Entertwonumbers(a0terminates):";
while(cin>>x>>y&&x*y!=0)
cout<<"harmonicmeanof"<<x<<"and"
<<y<<"="<<h_mean(x,y)<<"\n";
/*ordothereadingandtestingintwoparts:
while(cin>>x&&x!=0)
{
cin>>y;
if(y==0)
break;
...
*/
cout<<"Bye\n";
return0;
}
doubleh_mean(doublex,doubley)
{
return2.0*x*y/(x+y);
}
//pe7-3.cpp
#include<iostream>
structbox{
charmaker[40];
floatheight;
floatwidth;
floatlength;
floatvolume;
};
voidshowbox(boxb);
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 11 oI 65 September 2, 2004
voidsetbox(box*pb);
intmain(void)
{
boxcarton={"BingoBoxer",2,3,5};//novolumeprovided
setbox(&carton);
showbox(carton);
return0;
}
voidshowbox(boxb)
{
usingnamespacestd;
cout<<"Boxmaker:"<<b.maker
<<"\nheight:"<<b.height
<<"\nlwidth:"<<b.width
<<"\nlength:"<<b.length
<<"\nvolume:"<<b.volume<<"\n";
}
voidsetbox(box*pb)
{
pb->volume=pb->height*pb->width*pb->length;
}
//pe7-4.cpp-- probability ofwinning
#include<iostream>
longdoubleprobability(unsignednumbers,unsignedpicks);
intmain()
{
usingnamespacestd;
doubletotal,choices;
doublemtotal;
doubleprobability1,probability2;
cout<<"Entertotalnumberofgamecardchoicesand\n"
"numberofpicksallowedforthefield:\n";
while((cin>>total>>choices)&&choices<=total)
{
cout<<"Entertotalnumberofgamecardchoices"
"forthemeganumber:\n";
if(!(cin>>mtotal))
break;
cout<<"Thechancesofgettingall"<<choices<<"picksisonein
"
<<(probability1=probability(total,choices))<<".\n";
cout<<"Thechancesofgettingthemegaspotisonein"
<<(probability2=probability(mtotal,1))<<".\n";
cout<<"Youhaveonechancein";
cout<<probability1*probability2;//computetheprobability
cout<<"ofwinning.\n";
cout<<"Nextsetofnumbers(qtoquit):";
}
cout<<"bye\n";
return0;
}
//thefollowingfunctioncalculatestheprobabilityofpickingpicks
//numberscorrectlyfromnumberschoices
longdoubleprobability(unsignednumbers,unsignedpicks)
{
longdoubleresult=1.0;//herecomesomelocalvariables
longdoublen;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 12 oI 65 September 2, 2004
unsignedp;
for(n=numbers,p=picks;p>0;n--,p--)
result=result*n/p;
returnresult;
}
//pe7-6.cpp
#include<iostream>
intFill_array(doublear[],intsize);
voidShow_array(constdoublear[],intsize);
voidReverse_array(doublear[],intsize);
constintLIMIT=10;
intmain()
{
usingnamespacestd;
doublevalues[LIMIT];
intentries=Fill_array(values,LIMIT);
cout<<"Arrayvalues:\n";
Show_array(values,entries);
cout<<"Arrayreversed:\n";
Reverse_array(values,entries);
Show_array(values,entries);
cout<<"Allbutendvaluesreversed:\n";
Reverse_array(values+1,entries-2);
Show_array(values,entries);
return0;
}
intFill_array(doublear[],intsize)
{
usingnamespacestd;
intn;
cout<<"Enterupto"<<size<<"values(qtoquit):\n";
for(n=0;n<size;n++)
{
cin>>ar[n];
if(!cin)
break;
}
returnn;
}
voidShow_array(constdoublear[],intsize)
{
usingnamespacestd;
intn;
for(n=0;n<size;n++)
{
cout<<ar[n];
if(n%8==7)
cout<<endl;
else
cout<<'';
}
if(n%8!=0)
cout<<endl;
}
voidReverse_array(doublear[],intsize)
{
inti,j;
doubletemp;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 13 oI 65 September 2, 2004
for(i=0,j=size-1;i<j;i++,j--)
{
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
//pe7-9.cpp
#include<iostream>
doublecalculate(doublex,doubley,double(*pf)(double,double));
doubleadd(doublex,doubley);
doublesub(doublex,doubley);
doublemean(doublex,doubley);
intmain(void)
{
usingnamespacestd;
double(*pf[3])(double,double)={add,sub,mean};
char*op[3]={"sum","difference","mean"};
doublea,b;
cout<<"Enterpairsofnumbers(qtoquit):";
inti;
while(cin>>a>>b)
{
//usingfunctionnames
cout<<calculate(a,b,add)<<"=sum\n";
cout<<calculate(a,b,mean)<<"=mean\n";
//usingpointers
for(i=0;i<3;i++)
cout<<calculate(a,b,pf[i])<<"="
<<op[i]<<"\n";
}
cout<<"Done!\n";
return0;
}
doublecalculate(doublex,doubley,double(*pf)(double,double))
{
return(*pf)(x,y);
}
doubleadd(doublex,doubley)
{
returnx+y;
}
doublesub(doublex,doubley)
{
returnx-y;
}
doublemean(doublex,doubley)
{
return(x+y)/2.0;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 14 oI 65 September 2, 2004
Chapter 8
//pe8-1.cpp
#include<iostream>
voidsilly(constchar*s,intn=0);
intmain(void)
{
usingnamespacestd;
char*p1="Whyme?\n";
silly(p1);
for(inti=0;i<3;i++)
{
cout<<i<<"=i\n";
silly(p1,i);
}
cout<<"Done\n";
return0;
}
voidsilly(constchar*s,intn)
{
usingnamespacestd;
staticintuses=0;
intlim=++uses;
if(n==0)
lim=1;
for(inti=0;i<lim;i++)
cout<<s;
}
//pe8-4.cpp
#include<iostream>
#include<cstring>//forstrlen(),strcpy()
usingnamespacestd;
structstringy{
char*str;//pointstoastring
intct;//lengthofstring(notcounting'\0')
};
voidshow(constchar*str,intcnt=1);
voidshow(conststringy&bny,intcnt=1);
voidset(stringy&bny,constchar*str);
intmain(void)
{
stringybeany;
chartesting[]="Realityisn'twhatitusedtobe.";
set(beany,testing);//firstargumentisareference,
//allocatesspacetoholdcopyoftesting,
//setsstrmemberofbeanytopointtothe
//newblock,copiestestingtonewblock,
//andsetsctmemberofbeany
show(beany);//printsmemberstringonce
show(beany,2);//printsmemberstringtwice
testing[0]='D';
testing[1]='u';
show(testing);//printstestingstringonce
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 15 oI 65 September 2, 2004
show(testing,3);//printstestingstringthrice
show("Done!");
return0;
}
voidshow(constchar*str,intcnt)
{
while(cnt-->0)
{
cout<<str<<endl;
}
}
voidshow(conststringy&bny,intcnt)
{
while(cnt-->0)
{
cout<<bny.str<<endl;
}
}
voidset(stringy&bny,constchar*str)
{
bny.ct=strlen(str);
bny.str=newchar[bny.ct+1];
strcpy(bny.str,str);
}
//pe8-5.cpp
#include<iostream>
template<classT>
Tmax5(Tar[])
{
intn;
Tmax=ar[0];
for(n=1;n<5;n++)
if(ar[n]>max)
max=ar[n];
returnmax;
}
constintLIMIT=5;
intmain()
{
usingnamespacestd;
doubleard[LIMIT]={-3.4,8.1,-76.4,34.4,2.4};
intari[LIMIT]={2,3,8,1,9};
doublemd;
intmi;
md=max5(ard);
mi=max5(ari);
cout<<"md="<<md<<endl;
cout<<"mi="<<mi<<endl;
return0;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 16 oI 65 September 2, 2004
Chapter 9
PE 9-1

//pe9-golf.h-forpe9-1.cpp
constintLen=40;
structgolf
{
charfullname[Len];
inthandicap;
};
//non-interactiveversion
//functionsetsgolfstructuretoprovidedname,handicap
//usingvaluespassedasargumentstothefunction
voidsetgolf(golf&g,constchar*name,inthc);
//interactiveversion
//functionsolicitsnameandhandicapfromuser
//andsetsthemembersofgtothevaluesentered
//returns1ifnameisentered,0ifnameisemptystring
intsetgolf(golf&g);
//functionresetshandicaptonewvalue
voidhandicap(golf&g,inthc);
//functiondisplayscontentsofgolfstructure
voidshowgolf(constgolf&g);
//pe9-golf.cpp-forpe9-1.cpp
#include<iostream>
#include"pe9-golf.h"
#include<cstring>
//functionsolicitsnameandhandicapfromuser
//returns1ifnameisentered,0ifnameisemptystring
intsetgolf(golf&g)
{
std::cout<<"Pleaseentergolfer'sfullname:";
std::cin.getline(g.fullname,Len);
if(g.fullname[0]=='\0')
return0;//prematuretermination
std::cout<<"Pleaseenterhandicapfor"<<g.fullname<<":";
while(!(std::cin>>g.handicap))
{
std::cin.clear();
std::cout<<"Pleaseenteraninteger:";
}
while(std::cin.get()!='\n')
continue;
return1;
}
//functionsetsgolfstructuretoprovidedname,handicap
voidsetgolf(golf&g,constchar*name,inthc)
{
std::strcpy(g.fullname,name);
g.handicap=hc;
}
//functionresetshandicaptonewvalue
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 17 oI 65 September 2, 2004
voidhandicap(golf&g,inthc)
{
g.handicap=hc;
}
//functiondisplayscontentsofgolfstructure
voidshowgolf(constgolf&g)
{
std::cout<<"Golfer:"<<g.fullname<<"\n";
std::cout<<"Handicap:"<<g.handicap<<"\n\n";
}
//pe9-1.cpp
#include<iostream>
#include"pe9-golf.h"
//linkwithpe9-golf.cpp
constintMems=5;
intmain(void)
{
usingnamespacestd;
golfteam[Mems];
cout<<"Enterupto"<<Mems<<"golfteammembers:\n";
inti;
for(i=0;i<Mems;i++)
if(setgolf(team[i])==0)
break;
for(intj=0;j<i;j++)
showgolf(team[j]);
setgolf(team[0],"FredNorman",5);
showgolf(team[0]);
handicap(team[0],3);
showgolf(team[0]);
return0;
}
PE 9-3

//pe9-3.cpp--usingplacementnew
#include<iostream>
#include<new>
#include<cstring>
structchaff
{
chardross[20];
intslag;
};
//charbuffer[500];//option1
intmain()
{
usingstd::cout;
usingstd::endl;
chaff*p1;
inti;
char*buffer=newchar[500];//option2
p1=new(buffer)chaff[2];//placestructuresinbuffer
std::strcpy(p1[0].dross,"HorseFeathers");
p1[0].slag=13;
std::strcpy(p1[1].dross,"Piffle");
p1[1].slag=-39;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 18 oI 65 September 2, 2004
for(i=0;i<2;i++)
cout<<p1[i].dross<<":"<<p1[i].slag<<endl;
delete[]buffer;//option2
return0;
}
Chapter 10
PE 10-1

//pe10-1.cpp
#include<iostream>
#include<cstring>
//classdeclaration
classBankAccount
{
private:
charname[40];
characctnum[25];
doublebalance;
public:
BankAccount(char*client="noone",char*num="0",
doublebal=0.0);voidshow(void)const;
voiddeposit(doublecash);voidwithdraw(doublecash);
};
//methoddefinitions
BankAccount::BankAccount(char*client,char*num,doublebal)
{
std::strncpy(name,client,39);
name[39]='\0';
std::strncpy(acctnum,num,24);
acctnum[24]='\0';
balance=bal;
}
voidBankAccount::show(void)const
{
usingstd::cout;
usingstd::endl;
cout<<"Client:"<<name<<endl;
cout<<"AccountNumber:"<<acctnum<<endl;
cout<<"Balance:"<<balance<<endl;
}
voidBankAccount::deposit(doublecash)
{
if(cash>=0)
balance+=cash;
else
std::cout<<"Illegaltransactionattempted";
}
voidBankAccount::withdraw(doublecash)
{
if(cash<0)
std::cout<<"Illegaltransactionattempted";
elseif(cash<=balance)
balance-=cash;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 19 oI 65 September 2, 2004
else
std::cout<<"Requestdeniedduetoinsufficientfunds.\n";
}
//sampleuse
intmain()
{
BankAccountbird;
BankAccountfrog("Kermit","croak322",123.00);
bird.show();
frog.show();
bird=BankAccount("Chipper","peep8282",214.00);
bird.show();
frog.deposit(20);
frog.show();
frog.withdraw(4000);
frog.show();
frog.withdraw(50);
frog.show();
}
PE10-4

//pe10-4.h
#ifndefSALES__
#defineSALES__
namespaceSALES
{
constintQUARTERS=4;
classSales
{
private:
doublesales[QUARTERS];
doubleaverage;
doublemax;
doublemin;
public:
//defaultconstructor
Sales();
//copiesthelesserof4ornitemsfromthearrayar
//tothesalesmemberandcomputesandstoresthe
//average,maximum,andminimumvaluesoftheentereditems;
//remainingelementsofsales,ifany,setto0
Sales(constdoublear[],intn);
//gatherssalesfor4quartersinteractively,storesthem
//inthesalesmemberofobjectandcomputesandstoresthe
//average,maximum,andminumumvalues
voidsetSales();
//displayallinformationinobject
voidshowSales();
};
}
#endif
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 20 oI 65 September 2, 2004
//pe10-4a.cpp
#include<iostream>
#include"pe10-4.h"
intmain()
{
usingSALES::Sales;
doublevals[3]={2000,3000,5000};
SalesforFiji(vals,3);
forFiji.showSales();
Salesred;
red.showSales();
red.setSales();
red.showSales();
return0;
}
//pe10-4b.cpp
#include<iostream>
#include"pe10-4.h"
namespaceSALES
{
usingstd::cin;
usingstd::cout;
usingstd::endl;
Sales::Sales(constdoublear[],intn)
{
if(n<0)
n=0;
intlimit=n<QUARTERS?n:QUARTERS;
doubletotal=0;
min=0;
max=0;
average=0;
if(limit>0)
min=max=ar[0];
inti;
for(i=0;i<limit;i++)
{
sales[i]=ar[i];
total+=ar[i];
if(ar[i]>max)
max=ar[i];
elseif(ar[i]<min)
min=ar[i];
}
for(i=limit;i<QUARTERS;i++)
sales[i]=0;
if(limit>0)
average=total/limit;
}
Sales::Sales()
{
min=0;
max=0;
average=0;
for(inti=0;i<QUARTERS;i++)
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 21 oI 65 September 2, 2004
sales[i]=0;
}
voidSales::setSales()
{
doublesa[QUARTERS];
inti;
for(i=0;i<QUARTERS;i++)
{
cout<<"Entersalesforquarter"<<i+1<<":";
cin>>sa[i];
}
//createtemporaryobject,copytoinvokingobject
*this=Sales(sa,QUARTERS);
}
voidSales::showSales()
{
cout<<"Sales:\n";
for(inti=0;i<QUARTERS;i++)
cout<<"Quarter"<<i+1<<":$"
<<sales[i]<<endl;
cout<<"Average:$"<<average<<endl;
cout<<"Minimum:$"<<min<<endl;
cout<<"Maximum:$"<<max<<endl;
}
}
PE 10-5

//pe10stack.h--classdefinitionforthestackADT
//forusewithpe10-5.cpp
#ifndef_STACK_H_
#define_STACK_H_
structcustomer{
charfullname[35];
doublepayment;
};
typedefcustomerItem;
classStack
{
private:
enum{MAX=10};//constantspecifictoclass
Itemitems[MAX];//holdsstackitems
inttop;//indexfortopstackitem
public:
Stack();
boolisempty()const;
boolisfull()const;
//push()returnsfalseifstackalreadyisfull,trueotherwise
boolpush(constItem&item);//additemtostack
//pop()returnsfalseifstackalreadyisempty,trueotherwise
boolpop(Item&item);//poptopintoitem
};
#endif
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 22 oI 65 September 2, 2004
//pe10stack.cpp--Stackmemberfunctions
//forusewithpe10-5.cpp
//exactlythesameasstack.cppinthetext
#include"pe10stack.h"
Stack::Stack()//createanemptystack
{
top=0;
}
boolStack::isempty()const
{
returntop==0;
}
boolStack::isfull()const
{
returntop==MAX;
}
boolStack::push(constItem&item)
{
if(top<MAX)
{
items[top++]=item;
returntrue;
}
else
returnfalse;
}
boolStack::pop(Item&item)
{
if(top>0)
{
item=items[--top];
returntrue;
}
else
returnfalse;
}
//pe10-5.cpp
#include<iostream>
#include<cctype>
#include"pe10stack.h"//modifiedtodefinecustomerstructure
//linkwithpe10stack.cpp
voidget_customer(customer&cu);
intmain(void)
{
usingnamespacestd;
Stackst;//createastackofcustomerstructures
customertemp;
doublepayments=0;
charc;
cout<<"PleaseenterAtoaddacustomer,\n"
<<"Ptoprocessacustomer,andQtoquit.\n";
while(cin>>c&&(c=toupper(c))!='Q')
{
while(cin.get()!='\n')
continue;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 23 oI 65 September 2, 2004
if(c!='A'&&c!='P')
{
cout<<"PleaserespondwithA,P,orQ:";
continue;
}
switch(c)
{
case'A':if(st.isfull())
cout<<"stackalreadyfull\n";
else
{
get_customer(temp);
st.push(temp);
}
break;
case'P':if(st.isempty())
cout<<"stackalreadyempty\n";
else{
st.pop(temp);
payments+=temp.payment;
cout<<temp.fullname<<"processed.";
cout<<"Paymentsnowtotal$"
<<payments<<"\n";
}
break;
default:cout<<"Whoops!Programmingerror!\n";
}
cout<<"PleaseenterAtoaddacustomer,\n"
<<"Ptoprocessacustomer,andQtoquit.\n";
}
cout<<"Done!\n";
return0;
}
voidget_customer(customer&cu)
{
usingnamespacestd;
cout<<"Entercustomername:";
cin.getline(cu.fullname,35);
cout<<"Entercustomerpayment:";
cin>>cu.payment;
while(cin.get()!='\n')
continue;
}
PE 10-8

//pe10-8arr.h--headerfileforasimplelistclass
#ifndefSIMPLEST_
#defineSIMPLEST_
//program-specificdeclarations
constintTSIZE=45;//sizeofarraytoholdtitle
structfilm
{
chartitle[TSIZE];
intrating;
};
//generaltypedefinitions
typedefstructfilmItem;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 24 oI 65 September 2, 2004
constintMAXLIST=10;
classsimplist
{
private:
Itemitems[MAXLIST];
intcount;
public:
simplist(void);
boolisempty(void);
boolisfull(void);
intitemcount();
booladditem(Itemitem);
voidtransverse(void(*pfun)(Itemitem));
};
#endif
//pe10-8arr.cpp--functionssupportingsimplelistoperations
#include"pe10-8arr.h"
simplist::simplist(void)
{
count=0;
}
boolsimplist::isempty(void)
{
returncount==0;
}
boolsimplist::isfull(void)
{
returncount==MAXLIST;
}
intsimplist::itemcount()
{
returncount;
}
boolsimplist::additem(Itemitem)
{
if(count==MAXLIST)
returnfalse;
else
items[count++]=item;
returntrue;
}
voidsimplist::transverse(void(*pfun)(Itemitem))
{
for(inti=0;i<count;i++)
(*pfun)(items[i]);
}
//pe10-8.cpp--usingaclassdefinition
#include<iostream>
#include<cstdlib>//prototypeforexit()
#include"pe10-8arr.h"//simplelistclassdeclaration
//arrayversion
voidshowmovies(Itemitem);//tobeusedbytransverse()
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 25 oI 65 September 2, 2004
intmain(void)
{
usingnamespacestd;
simplistmovies;//createsanemptylist
Itemtemp;
if(movies.isfull())//invokesisfull()memberfunction
{
cout<<"Nomoreroominlist!Bye!\n";
exit(1);
}
cout<<"Enterfirstmovietitle:\n";
while(cin.getline(temp.title,TSIZE)&&temp.title[0]!='\0')
{
cout<<"Enteryourrating<0-10>:";
cin>>temp.rating;
while(cin.get()!='\n')
continue;
if(movies.additem(temp)==false)
{
cout<<"Listalreadyisfull!\n";
break;
}
if(movies.isfull())
{
cout<<"Youhavefilledthelist.\n";
break;
}
cout<<"Enternextmovietitle(emptylinetostop):\n";
}
if(movies.isempty())
cout<<"Nodataentered.";
else
{
cout<<"Hereisthemovielist:\n";
movies.transverse(showmovies);
}
cout<<"Bye!\n";
return0;
}
voidshowmovies(Itemitem)
{
std::cout<<"Movie:"<<item.title<<"Rating:"
<<item.rating<<std::endl;
}
Chapter 11
PE11-2
//pe11-2.h--Vectorclasswith<<,modestate
//modifiedimplementation
#ifndefMODVECTOR_H_
#defineMODVECTOR_H_
#include<iostream>
namespaceVECTOR
{
usingstd::ostream;
classVector
{
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 26 oI 65 September 2, 2004
private:
doublex;//horizontalvalue
doubley;//verticalvalue
charmode;//'r'=rectangular,'p'=polar
//privatemethodsforsettingvalues
voidset_mag();
voidset_ang();
voidset_x(double,double);
voidset_y(double,double);
public:
Vector();
Vector(doublen1,doublen2,charform='r');
voidset(doublen1,doublen2,charform='r');
~Vector();
doublexval()const{returnx;}//reportxvalue
doubleyval()const{returny;}//reportyvalue
doublemagval()const;//reportmagnitude
doubleangval()const;//reportangle
voidpolar_mode();//setmodeto'p'
voidrect_mode();//setmodeto'r'
//operatoroverloading
Vectoroperator+(constVector&b)const;
Vectoroperator-(constVector&b)const;
Vectoroperator-()const;
Vectoroperator*(doublen)const;
//friends
friendVectoroperator*(doublen,constVector&a);
friendostream&operator<<(ostream&os,constVector&v);
};
}//endnamespaceVECTOR
#endif
//pe11-2.cpp--modifiedmethodsforVectorclass
#include<cmath>
#include"pe11-2.h"//includes<iostream>
usingstd::sqrt;
usingstd::sin;
usingstd::cos;
usingstd::atan2;
usingstd::cout;
namespaceVECTOR
{
constdoubleRad_to_deg=57.2957795130823;
//privatemethods
//calculatesmagnitudefromxandy
//setxfrompolarcoordinate
voidVector::set_x(doublemag,doubleang)
{
x=mag*cos(ang);
}
//setyfrompolarcoordinate
voidVector::set_y(doublemag,doubleang)
{
y=mag*sin(ang);
}
//publicmethods
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 27 oI 65 September 2, 2004
Vector::Vector()//defaultconstructor
{
x=y=0.0;
mode='r';
}
//constructvectorfromrectangularcoordinatesifformisr
//(thedefault)orelsefrompolarcoordinatesifformisp
Vector::Vector(doublen1,doublen2,charform)
{
mode=form;
if(form=='r')
{
x=n1;
y=n2;
}
elseif(form=='p')
{
set_x(n1,n2/Rad_to_deg);
set_y(n1,n2/Rad_to_deg);
}
else
{
cout<<"Incorrect3rdargumenttoVector()--";
cout<<"vectorsetto0\n";
x=y=0.0;
mode='r';
}
}
//setvectorfromrectangularcoordinatesifformisr(the
//default)orelsefrompolarcoordinatesifformisp
voidVector::set(doublen1,doublen2,charform)
{
mode=form;
if(form=='r')
{
x=n1;
y=n2;
}
elseif(form=='p')
{
set_x(n1,n2/Rad_to_deg);
set_y(n1,n2/Rad_to_deg);
}
else
{
cout<<"Incorrect3rdargumenttoVector()--";
cout<<"vectorsetto0\n";
x=y=0.0;
mode='r';
}
}
Vector::~Vector()//destructor
{
}
doubleVector::magval()const//reportmagnitude
{
returnsqrt(x*x+y*y);
}
doubleVector::angval()const//reportangle
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 28 oI 65 September 2, 2004
{
if(x==0.0&&y==0.0)
return0;
else
returnatan2(y,x);
}
voidVector::polar_mode()//settopolarmode
{
mode='p';
}
voidVector::rect_mode()//settorectangularmode
{
mode='r';
}
//operatoroverloading
//addtwoVectors
VectorVector::operator+(constVector&b)const
{
returnVector(x+b.x,y+b.y);
}
//subtractVectorbfroma
VectorVector::operator-(constVector&b)const
{
returnVector(x-b.x,y-b.y);
}
//reversesignofVector
VectorVector::operator-()const
{
returnVector(-x,-y);
}
//multiplevectorbyn
VectorVector::operator*(doublen)const
{
returnVector(n*x,n*y);
}
//friendmethods
//multiplynbyVectora
Vectoroperator*(doublen,constVector&a)
{
returna*n;
}
//displayrectangularcoordinatesifmodeisr,
//elsedisplaypolarcoordinatesifmodeisp
ostream&operator<<(ostream&os,constVector&v)
{
if(v.mode=='r')
os<<"(x,y)=("<<v.x<<","<<v.y<<")";
elseif(v.mode=='p')
{
os<<"(m,a)=("<<v.magval()<<","
<<v.angval()*Rad_to_deg<<")";
}
else
os<<"Vectorobjectmodeisinvalid";
returnos;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 29 oI 65 September 2, 2004
}//endnamespaceVECTOR
//pe11-2walk.cpp--usethemodifiedVectorclass
//compilewiththevect.cppfile
#include<iostream>
#include<cstdlib>//rand(),srand()prototypes
#include<ctime>//time()prototype
#include"pe11-2.h"
intmain()
{
usingnamespacestd;
usingVECTOR::Vector;
srand(time(0));//seedrandom-numbergenerator
doubledirection;
Vectorstep;
Vectorresult(0.0,0.0);
unsignedlongsteps=0;
doubletarget;
doubledstep;
cout<<"Entertargetdistance(qtoquit):";
while(cin>>target)
{
cout<<"Entersteplength:";
if(!(cin>>dstep))
break;
while(result.magval()<target)
{
direction=rand()%360;
step.set(dstep,direction,'p');
result=result+step;
steps++;
}
cout<<"After"<<steps<<"steps,thesubject"
"hasthefollowinglocation:\n";
cout<<result<<endl;
result.polar_mode();
cout<<"or\n"<<result<<endl;
cout<<"Averageoutwarddistanceperstep="
<<result.magval()/steps<<endl;
steps=0;
result.set(0.0,0.0);
cout<<"Entertargetdistance(qtoquit):";
}
cout<<"Bye!\n";
return0;
}
PE 11-5

//pe11ston.h--definitionforStonewtclass(forpe11-5)
#ifndefPE11STONEWT_H_
#definePE11STONEWT_H_
#include<iostream>
classStonewt
{
private:
enum{Lbs_per_stn=14};//poundsperstone
intstone;//wholestones
doublepds_left;//fractionalpounds
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 30 oI 65 September 2, 2004
doublepounds;//entireweightinpounds
charmode;//displaymodeforweight
//'s'=stone,'f'=float,'w'=wholepounds
public:
Stonewt(doublelbs);//constructorfordoublepounds
Stonewt(intstn,doublelbs);//constructorforstone,lbs
Stonewt();//defaultconstructor
~Stonewt();
voidset_mode(charm){mode=m;}
Stonewtoperator+(constStonewt&sw)const;
Stonewtoperator-(constStonewt&sw)const;
Stonewtoperator*(doublem)const;
friendStonewtoperator*(doublem,constStonewt&sw)
{returnsw*m;}
friendstd::ostream&operator<<(std::ostream&os,constStonewt&sw);
};
#endif
//pe11ston.h--definitionforStonewtclass(forpe11-5)
#ifndefPE11STONEWT_H_
#definePE11STONEWT_H_
#include<iostream>
classStonewt
{
private:
enum{Lbs_per_stn=14};//poundsperstone
intstone;//wholestones
doublepds_left;//fractionalpounds
doublepounds;//entireweightinpounds
charmode;//displaymodeforweight
//'s'=stone,'f'=float,'w'=wholepounds
public:
Stonewt(doublelbs);//constructorfordoublepounds
Stonewt(intstn,doublelbs);//constructorforstone,lbs
Stonewt();//defaultconstructor
~Stonewt();
voidset_mode(charm){mode=m;}
Stonewtoperator+(constStonewt&sw)const;
Stonewtoperator-(constStonewt&sw)const;
Stonewtoperator*(doublem)const;
friendStonewtoperator*(doublem,constStonewt&sw)
{returnsw*m;}
friendstd::ostream&operator<<(std::ostream&os,constStonewt&sw);
};
#endif
//pe11-5.cpp
#include<iostream>
#include"pe11ston.h"
//linkwithpe11ston.cpp
intmain(void)
{
usingstd::cout;
Stonewtfullback(245.5);
Stonewtcornerback(13,5.2);
cout<<fullback;
cout<<cornerback;
cornerback.set_mode('w');
cout<<cornerback;
Stonewtlump;
lump=fullback+cornerback;
cout<<lump;
fullback=fullback*1.1;
cout<<fullback;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 31 oI 65 September 2, 2004
lump=lump-fullback;
cout<<lump;
lump=1.3*lump;
lump.set_mode('s');
cout<<lump;
return0;
}
PE 11-7

//pe11-7.cpp
#include<iostream>
#include"complex0.h"//toavoidconfusionwithcomplex.h
intmain()
{
usingstd::cout;
usingstd::endl;
usingstd::cin;
complexa(3.0,4.0);//initializeto(3,4i)
complexc;
cout<<"Enteracomplexnumber(qtoquit):\n";
while(cin>>c)
{
cout<<"cis"<<c<<endl;
cout<<"complexconjugateis"<<~c<<endl;
cout<<"ais"<<a<<endl;
cout<<"a+cis"<<a+c<<endl;
cout<<"a-cis"<<a-c<<endl;
cout<<"a*cis"<<a*c<<endl;
cout<<"2*cis"<<2*c<<endl;
cout<<"Enteracomplexnumber(qtoquit):\n";
}
cout<<"Done!\n";
return0;
}
//complex0.h
#ifndefCOMPLEX0_H_
#defineCOMPLEX0_H_
#include<iostream>
classcomplex
{
private:
doubler;
doublei;
public:
complex();
complex(doublereal);
complex(doublereal,doubleimag);
doublemagnitude();
complexoperator+(constcomplex&z)const;
complexoperator-(constcomplex&z)const;
complexoperator~()const;
friendcomplexsquare(constcomplex&z);
friendcomplexoperator*(constcomplex&z,constcomplex&w);
friendstd::ostream&operator<<(std::ostream&os,constcomplex&z);
friendstd::istream&operator>>(std::istream&is,complex&z);
};
#endif
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 32 oI 65 September 2, 2004
//complex0.cpp
#include<iostream>
#include<cmath>
#include"complex0.h"
complex::complex()
{
r=i=0.0;
}
complex::complex(doublereal)
{
r=real;
i=0.0;
}
complex::complex(doublereal,doubleimag)
{
r=real;
i=imag;
}
doublecomplex::magnitude()
{
returnstd::sqrt(r*r+i*i);
}
complexcomplex::operator+(constcomplex&z)const
{
complexsum;
sum.r=r+z.r;
sum.i=i+z.i;
returnsum;
}
complexcomplex::operator-(constcomplex&z)const
{
complexsum;
sum.r=r+z.r;
sum.i=i+z.i;
returnsum;
}
complexcomplex::operator~()const
{
complexconjugate;
conjugate.r=r;
conjugate.i=-i;
returnconjugate;
}
complexsquare(constcomplex&z)
{
complexsq;
sq.r=z.r*z.r-z.i*z.i;
sq.i=2.0*z.r*z.i;
returnsq;
}
complexoperator*(constcomplex&z,constcomplex&w)
{
complexsq;
sq.r=w.r*z.r-w.i*z.i;
sq.i=w.r*z.i+w.i*z.r;
returnsq;
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 33 oI 65 September 2, 2004
std::ostream&operator<<(std::ostream&os,constcomplex&z)
{
os<<'('<<z.r<<','<<z.i<<"i)";
returnos;
}
std::istream&operator>>(std::istream&is,complex&z)
{
std::cout<<"real:";
if(is>>z.r)
{
std::cout<<"imaginary:";
is>>z.i;
}
returnis;
}
Chapter 12
PE 12-2

//pe12-2.cpp
#include<iostream>
//#include"string2.h"
#include"pe12strg.h"//alternativename
intmain()
{
usingstd::cout;
usingstd::cin;
Strings1("andIamaC++student.");
Strings2="Pleaseenteryourname:";
Strings3;
cout<<s2;//overloaded<<operator
cin>>s3;//overloaded>>operator
s2="Mynameis"+s3;//overloaded=,+operators
cout<<s2<<".\n";
s2=s2+s1;
s2.stringup();//convertsstringtouppercase
cout<<"Thestring\n"<<s2<<"\ncontains"<<s2.has('A')
<<"'A'charactersinit.\n";
s1="red";//String(constchar*),
//thenString&operator=(constString&)
Stringrgb[3]={String(s1),String("green"),String("blue")};
cout<<"Enterthenameofaprimarycolorformixinglight:";
Stringans;
boolsuccess=false;
while(cin>>ans)
{
ans.stringlow();//convertsstringtolowercase
for(inti=0;i<3;i++)
{
if(ans==rgb[i])//overloaded==operator
{
cout<<"That'sright!\n";
success=true;
break;
}
}
if(success)
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 34 oI 65 September 2, 2004
break;
else
cout<<"Tryagain!\n";
}
cout<<"Bye\n";
return0;
}
//pe12strg.h
#ifndefPE12STRG_H_
#definePE12STRG_H_
#include<iostream>
classString{
private:
char*str;//pointertoastring
intchars;//numberofcharacters
staticintstrings;//totalnumberofstrings
public:
String();
String(constchar*ps);//convertsC++stringtoString
String(constString&s);
~String();
intnumstrings();
intlen();
voidstringup();
voidstringlow();
inthas(charch);
String&operator=(constString&s);
friendstd::ostream&operator<<(std::ostream&os,constString&s);
friendstd::istream&operator>>(std::istream&os,String&s);
friendStringoperator+(constString&s1,constString&s2);
friendintoperator==(constString&s1,constString&s2);
friendintoperator<(constString&s1,constString&s2);
friendintoperator>(constString&s1,constString&s2);
};
#endif
//pe12strg.cpp
#include<iostream>
#include<cctype>
//#include"string2.h"
#include"pe12strg.h"//alternativename
intString::strings=0;
String::String()
{
str=NULL;
chars=0;
strings++;
}
String::String(constchar*ps)
{
chars=std::strlen(ps);
str=newchar[chars+1];
std::strcpy(str,ps);
strings++;
}
String::String(constString&s)
{
chars=s.chars;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 35 oI 65 September 2, 2004
str=newchar[chars+1];
std::strcpy(str,s.str);
strings++;
}
String::~String()
{
strings--;
delete[]str;
}
intString::numstrings()
{
returnstrings;
}
intString::len()
{
returnchars;
}
voidString::stringup()
{
for(inti=0;i<chars;i++)
str[i]=std::toupper(str[i]);
}
voidString::stringlow()
{
for(inti=0;i<chars;i++)
str[i]=std::tolower(str[i]);
}
String&String::operator=(constString&s)//allowschaining
{
if(this==&s)//assignmenttoself
return*this;
delete[]str;//freeoldcontents,ifany
chars=s.chars;
str=newchar[chars+1];
std::strcpy(str,s.str);
return*this;
}
std::ostream&operator<<(std::ostream&os,constString&s)
{
os<<s.str;
returnos;
}
std::istream&operator>>(std::istream&is,String&s)
{
chartemp[80];
is.getline(temp,80);
s=temp;
returnis;
}
Stringoperator+(constString&s1,constString&s2)
{
intlen=s1.chars+s2.chars;
char*ps=newchar[len+1];
std::strcpy(ps,s1.str);
std::strcat(ps,s2.str);
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 36 oI 65 September 2, 2004
Stringtemp(ps);
returntemp;
}
intString::has(charch)
{
intct=0;
char*ps=str;
while(*ps)
{
if(*ps++==ch)
++ct;
}
returnct;
}
intoperator==(constString&s1,constString&s2)
{
if(s1.chars!=s2.chars)
return0;
elseif(std::strcmp(s1.str,s2.str)==0)
return1;
else
return0;
}
intoperator<(constString&s1,constString&s2)
{
if(std::strcmp(s1.str,s2.str)<0)
return1;
else
return0;
}
intoperator>(constString&s1,constString&s2)
{
if(std::strcmp(s1.str,s2.str)>0)
return1;
else
return0;
}
PE 12-4

//pe12stak.h--classdefinitionforthestackADT
#ifndefPE12STAK_H_
#definePE12STAK_H_
typedefunsignedlongItem;
classStack
{
private:
enum{MAX=10};//constantspecifictoclass
Item*pitems;//holdsstackitems
intsize;//maxnumberofelementsinstack
inttop;//indexfortopstackitem
Stack(constStack&st){}//nocopyingofstacks
Stack&operator=(constStack&st){return*this;}//noassignment
public:
Stack(intn=MAX);
~Stack();
boolisempty()const;
boolisfull()const;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 37 oI 65 September 2, 2004
//push()returnsfalseifstackalreadyisfull,trueotherwise
boolpush(constItem&item);//additemtostack
//pop()returnsfalseifstackalreadyisempty,trueotherwise
boolpop(Item&item);//poptopintoitem
};
#endif
//pe12stak.cpp--Stackmemberfunctions
#include"pe12stak.h"
Stack::Stack(intn)//createanemptystack
{
size=n;
pitems=newItem[size];
top=0;
}
Stack::~Stack(){delete[]pitems;}
boolStack::isempty()const
{
returntop==0?true:false;
}
boolStack::isfull()const
{
returntop==size?true:false;
}
boolStack::push(constItem&item)
{
if(top<size)
{
pitems[top++]=item;
returntrue;
}
else
returnfalse;
}
boolStack::pop(Item&item)
{
if(top>0)
{
item=pitems[--top];
returntrue;
}
else
returnfalse;
}
//pe12-4.cpp
#include<iostream>
#include<cctype>
#include"pe12stak.h"//modifiedtodefinecustomerstructure
//linkwithpe12stak.cpp
intmain(void)
{
usingnamespacestd;
Stackst(3);//createastackofponumbers
unsignedlongtemp;
charc;
cout<<"PleaseenterAtoaddaPO,\n"
<<"PtoprocessaPO,andQtoquit.\n";
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 38 oI 65 September 2, 2004
while(cin>>c&&(c=toupper(c))!='Q')
{
while(cin.get()!='\n')
continue;
if(c!='A'&&c!='P')
{
cout<<"PleaserespondwithA,P,orQ:";
continue;
}
switch(c)
{
case'A':if(st.isfull())
cout<<"stackalreadyfull\n";
else
{
cout<<"EnterPOnumber:";
cin>>temp;
st.push(temp);
}
break;
case'P':if(st.isempty())
cout<<"stackalreadyempty\n";
else{
st.pop(temp);
cout<<"ProcessingPO"<<temp<<'\n';
}
break;
default:cout<<"Whoops!Programmingerror!\n";
}
cout<<"PleaseenterAtoaddacustomer,\n"
<<"Ptoprocessacustomer,andQtoquit.\n";
}
cout<<"Done!\n";
return0;
}
PE 12-6

//pe12que.h--interfaceforaqueue
#ifndef_QUEUE_H_
#define_QUEUE_H_
//ThisqueuewillcontainCustomeritems
classCustomer
{
private:
longarrive;//arrivaltimeforcustomer
intprocesstime;//processingtimeforcustomer
public:
Customer(){arrive=processtime=0;}
voidset(longwhen);
longwhen()const{returnarrive;}
intptime()const{returnprocesstime;}
};
typedefCustomerItem;
classQueue
{
private:
//classscopedefinitions
//Nodeisanestedstructuredefinitionlocaltothisclass
structNode{Itemitem;structNode*next;};
enum{Q_SIZE=10};
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 39 oI 65 September 2, 2004
//privateclassmembers
Node*front;//pointertofrontofQueue
Node*rear;//pointertorearofQueue
intitems;//currentnumberofitemsinQueue
constintqsize;//maximumnumberofitemsinQueue
//preemptivedefinitionstopreventpubliccopying
Queue(constQueue&q):qsize(0){}
Queue&operator=(constQueue&q){return*this;}
public:
Queue(intqs=Q_SIZE);//createqueuewithaqslimit
~Queue();
boolisempty()const;
boolisfull()const;
intqueuecount()const;
boolenqueue(constItem&item);//additemtoend
booldequeue(Item&item);//removeitemfromfront
};
#endif
//pe12que.cpp--QueueandCustomermethods
#include"pe12que.h"
#include<cstdlib>//(orstdlib.h)forrand()
usingstd::rand;
//Queuemethods
Queue::Queue(intqs):qsize(qs)
{
front=rear=NULL;
items=0;
}
Queue::~Queue()
{
Node*temp;
while(front!=NULL)//whilequeueisnotyetempty
{
temp=front;//saveaddressoffrontitem
front=front->next;//resetpointertonextitem
deletetemp;//deleteformerfront
}
}
boolQueue::isempty()const
{
returnitems==0;
}
boolQueue::isfull()const
{
returnitems==qsize;
}
intQueue::queuecount()const
{
returnitems;
}
//Additemtoqueue
boolQueue::enqueue(constItem&item)
{
if(isfull())
returnfalse;
Node*add=newNode;//createnode
if(add==NULL)
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 40 oI 65 September 2, 2004
returnfalse;//quitifnoneavailable
add->item=item;//setnodepointers
add->next=NULL;
items++;
if(front==NULL)//ifqueueisempty,
front=add;//placeitematfront
else
rear->next=add;//elseplaceatrear
rear=add;//haverearpointtonewnode
returntrue;
}
//Placefrontitemintoitemvariableandremovefromqueue
boolQueue::dequeue(Item&item)
{
if(front==NULL)
returnfalse;
item=front->item;//setitemtofirstiteminqueue
items--;
Node*temp=front;//savelocationoffirstitem
front=front->next;//resetfronttonextitem
deletetemp;//deleteformerfirstitem
if(items==0)
rear=NULL;
returntrue;
}
//customermethod
//whenisthetimeatwhichthecustomerarrives
//thearrivaltimeissettowhenandtheprocessing
//timesettoarandomvalueintherange1-3
voidCustomer::set(longwhen)
{
processtime=std::rand()%3+1;
arrive=when;
}
//pe12-6.cpp--usetheQueueinterface
//linktope12que.cpp
//modifyListing12.10byaddingasecondqueue
#include<iostream>
#include<ctime>//fortime()
#include<cstdlib>//forrand()andsrand()
#include"pe12que.h"
constlongMIN_PER_HR=60L;
boolnewcustomer(doublex);//isthereanewcustomer?
intmain(void)
{
usingstd::cin;
usingstd::cout;
usingstd::endl;
usingstd::ios_base;
//settingthingsup
std::srand(std::time(0));//randominitializingofrand()
cout<<"CaseStudy:BankofHeatherAutomaticTeller\n";
cout<<"Entermaximumsizeofeachqueue:";
intqs;
cin>>qs;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 41 oI 65 September 2, 2004
Queueline1(qs);//linequeueholdsuptoqspeople
Queueline2(qs);//secondqueue
cout<<"Enterthenumberofsimulationhours:";
inthours;//hoursofsimulation
cin>>hours;
//simulationwillrun1cycleperminute
longcyclelimit=MIN_PER_HR*hours;//#ofcycles
Itemtemp;//newcustomerdata
longturnaways;//turnedawaybyfullqueue
longcustomers;//joinedthequeue
longserved;//servedduringthesimulation
longsum_line;//cumulativelinelength
intwait_time1;//timeuntilautoteller1isfree
intwait_time2;//timeuntilautoteller2isfree
longline_wait;//cumulativetimeinline
doublemin_per_cust;//averagetimebetweenarrivals
cout<<"Entertheaveragenumberofcustomersperhour:";
doubleperhour;//average#ofarrivalperhour
cin>>perhour;
while(perhour>0)//beginnewloop
{
min_per_cust=MIN_PER_HR/perhour;
turnaways=0;
customers=0;
served=0;
sum_line=0;
wait_time1=wait_time2=0;
line_wait=0;
//runningthesimulation
for(longcycle=0;cycle<cyclelimit;cycle++)
{
if(newcustomer(min_per_cust))//havenewcomer
{
if(line1.isfull()&&line2.isfull())
turnaways++;
else//atleastonelineisnotfull
{
customers++;
temp.set(cycle);//cycle=timeofarrival
//addcustomertoshorterline
if(line1.queuecount()<=line2.queuecount())
line1.enqueue(temp);//addnewcomertoline1
else
line2.enqueue(temp);//addnewcomertoline2
}
}
//processcustomersinfirstqueue
if(wait_time1<=0&&!line1.isempty())
{
line1.dequeue(temp);//attendnextcustomer
wait_time1=temp.ptime();//forwait_timeminutes
line_wait+=cycle-temp.when();
served++;
}
if(wait_time1>0)
wait_time1--;
sum_line+=line1.queuecount();
//processcustomersinsecondqueue
if(wait_time2<=0&&!line2.isempty())
{
line2.dequeue(temp);//attendnextcustomer
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 42 oI 65 September 2, 2004
wait_time2=temp.ptime();//forwait_timeminutes
line_wait+=cycle-temp.when();
served++;
}
if(wait_time2>0)
wait_time2--;
sum_line+=line2.queuecount();
}
//reportingresults
if(customers>0)
{
cout<<"customersaccepted:"<<customers<<'\n';
cout<<"customersserved:"<<served<<'\n';
cout<<"turnaways:"<<turnaways<<'\n';
cout<<"averagequeuesize:";
cout.precision(2);
cout.setf(ios_base::fixed,ios_base::floatfield);
cout.setf(ios_base::showpoint);
cout<<(double)sum_line/cyclelimit<<'\n';
cout<<"averagewaittime:"
<<(double)line_wait/served<<"minutes\n";
}
else
cout<<"Nocustomers!\n";
//clearqueues
while(!line1.isempty())
line1.dequeue(temp);
while(!line2.isempty())
line2.dequeue(temp);
cout<<"Enternewvalueforcustomersperhour(0toquit):";
cin>>perhour;
}//endofnewloop
cout<<"Bye\n";
return0;
}
//x=averagetime,inminutes,betweencustomers
//returnvalueistrueifcustomershowsupthisminute
boolnewcustomer(doublex)
{
if(std::rand()*x/RAND_MAX<1)
returntrue;
else
returnfalse;
}
Chapter 13
PE 13-1

//cd.h--baseclass
#ifndefCD_H_
#defineCD_H_
classCd{//representsaCDdisk
private:
charperformers[50];
charlabel[20];
intselections;//numberofselections
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 43 oI 65 September 2, 2004
doubleplaytime;//playingtimeinminutes
public:
Cd(constchar*s1,constchar*s2,intn,doublex);
//Cd(constCd&d);//defaultversionisfine
Cd();
virtual~Cd(){}
virtualvoidReport()const;//reportsallCDdata
//Cd&operator=(constCd&d);//defaultversionisfine
};
#endif
//pe13-1cd.cpp--cdmethods
#include<iostream>
#include<cstring>
#include"cd.h"
Cd::Cd(constchar*s1,constchar*s2,intn,doublex)
{
std::strncpy(performers,s1,49);
performers[49]='\0';
std::strncpy(label,s2,19);
label[19]='\0';
selections=n;
playtime=x;
}
Cd::Cd()
{
performers[0]='\0';
label[0]='\0';
selections=0;
playtime=0.0;
}
voidCd::Report()const
{
usingstd::cout;
usingstd::endl;
cout<<"Performer(s):"<<performers<<endl;
cout<<"Label:"<<label<<endl;
cout<<"Numberofselections:"<<selections<<endl;
cout<<"Playtime:"<<playtime<<endl;
}
//classic.h
//derivedclass
#ifndefCLASSIC_H_
#defineCLASSIC_H_
#include"cd.h"
classClassic:publicCd
{
private:
charprimarywork[50];
public:
Classic(constchar*pw,constchar*s1,constchar*s2,
intn,doublex);
Classic();
voidReport()const;//redefinetoreportprimarywork
};
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 44 oI 65 September 2, 2004
#endif
//pe13-1cl.cpp
//Classicmethods
#include<iostream>
#include<cstring>
#include"classic.h"
Classic::Classic(constchar*pw,constchar*s1,
constchar*s2,intn,doublex)
:Cd(s1,s2,n,x)
{
std::strncpy(primarywork,pw,49);
primarywork[49]='\0';
}
Classic::Classic():Cd()
{
primarywork[0]='\0';
}
voidClassic::Report()const
{
std::cout<<"Primarywork:"<<primarywork<<std::endl;
Cd::Report();
}
//pe13-1.cpp
#include<iostream>
usingnamespacestd;
#include"classic.h"//whichwillcontain#includecd.h
voidBravo(constCd&disk);
intmain()
{
Cdc1("Beatles","Capitol",14,35.5);
Classicc2=Classic("PianoSonatainBflat,FantasiainC",
"AlfredBrendel","Philips",2,57.17);
Cd*pcd=&c1;
cout<<"Usingobjectdirectly:\n";
c1.Report();//useCdmethod
c2.Report();//useClassicmethod
cout<<"Usingtypecd*pointertoobjects:\n";
pcd->Report();//useCdmethodforcdobject
pcd=&c2;
pcd->Report();//useClassicmethodforclassicobject
cout<<"CallingafunctionwithaCdreferenceargument:\n";
Bravo(c1);
Bravo(c2);
cout<<"Testingassignment:";
Classiccopy;
copy=c2;
copy.Report();
return0;
}
voidBravo(constCd&disk)
{
disk.Report();
}
Foxit Reader -
(C) Foxit Software Company,2005-2006

Solutions Ior Programming Exercises in C Primer Plus, 5


th
Edition
SP 45 oI 65 September 2, 2004
PE 13-3

//pe13dma.h--inheritanceanddynamicmemoryallocation
#ifndefDMA_H_
#defineDMA_H_
#include<iostream>
//AbstractBaseClass
classABC
{
private:
char*label;
intrating;
public:
ABC(constchar*l="null",intr=0);
ABC(constABC&rs);
virtual~ABC()=0;
virtualABC&operator*(){return*this;}
ABC&operator=(constABC&rs);
virtualvoidView()const;
friendstd::ostream&operator<<(std::ostream&os,constABC&rs);
};
//FormerBaseClassUsingDMA
classbaseDMA:publicABC
{
private:
public:
baseDMA(constchar*l="null",intr=0);
};
//derivedclasswithoutDMA
//nodestructorneeded
//usesimplicitcopyconstructor
//usesimplicitassignmentoperator
classlacksDMA:publicABC
{
private:
charcolor[40];
public:
lacksDMA(constchar*c="blank",constchar*l="null",
intr=0);
lacksDMA(constchar*c,constABC&rs);
voidView()const;
};
//derivedclasswithDMA
classhasDMA:publicABC
{
private:
char*style;
public:
hasDMA(constchar*s="none",constchar*l="null",
intr=0);
hasDMA(constchar*s,constABC&rs);
hasDMA(consthasDMA&hs);
~hasDMA();
hasDMA&operator=(consthasDMA&rs);
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 46 oI 65 September 2, 2004
voidView()const;
};
#endif
//pe13dma.cpp--dmaclassmethods
#include"pe13dma.h"
#include<cstring>
//ABCmethods
ABC::ABC(constchar*l,intr)
{
label=newchar[std::strlen(l)+1];
std::strcpy(label,l);
rating=r;
}
ABC::ABC(constABC&rs)
{
label=newchar[std::strlen(rs.label)+1];
std::strcpy(label,rs.label);
rating=rs.rating;
}
ABC::~ABC()
{
delete[]label;
}
ABC&ABC::operator=(constABC&rs)
{
if(this==&rs)
return*this;
delete[]label;
label=newchar[std::strlen(rs.label)+1];
std::strcpy(label,rs.label);
rating=rs.rating;
return*this;
}
voidABC::View()const
{
std::cout<<"Label:"<<label<<std::endl;
std::cout<<"Rating:"<<rating<<std::endl;
}
std::ostream&operator<<(std::ostream&os,constABC&rs)
{
rs.View();
returnos;
}
//baseDMAmethods
baseDMA::baseDMA(constchar*l,intr):ABC(l,r)
{
}
//lacksDMAmethods
lacksDMA::lacksDMA(constchar*c,constchar*l,intr)
:ABC(l,r)
{
std::strncpy(color,c,39);
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 47 oI 65 September 2, 2004
color[39]='\0';
}
lacksDMA::lacksDMA(constchar*c,constABC&rs)
:ABC(rs)
{
std::strncpy(color,c,39);
color[39]='\0';
}
voidlacksDMA::View()const
{
ABC::View();
std::cout<<"Color:"<<color<<std::endl;
}
//hasDMAmethods
hasDMA::hasDMA(constchar*s,constchar*l,intr)
:ABC(l,r)
{
style=newchar[std::strlen(s)+1];
std::strcpy(style,s);
}
hasDMA::hasDMA(constchar*s,constABC&rs)
:ABC(rs)
{
style=newchar[std::strlen(s)+1];
std::strcpy(style,s);
}
hasDMA::hasDMA(consthasDMA&hs)
:ABC(hs)//invokebaseclasscopyconstructor
{
style=newchar[std::strlen(hs.style)+1];
std::strcpy(style,hs.style);
}
hasDMA::~hasDMA()
{
delete[]style;
}
hasDMA&hasDMA::operator=(consthasDMA&hs)
{
if(this==&hs)
return*this;
ABC::operator=(hs);//copybaseportion
style=newchar[std::strlen(hs.style)+1];
std::strcpy(style,hs.style);
return*this;
}
voidhasDMA::View()const
{
ABC::View();
std::cout<<"Style:"<<style<<std::endl;
}
//pe13-3.cpp--inheritance,friends,andDMA
//compilewithpe13dma.cpp
#include<iostream>
#include"pe13dma.h"
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 48 oI 65 September 2, 2004
intmain()
{
usingstd::cout;
usingstd::endl;
baseDMAshirt("Portabelly",8);
lacksDMAballoon("red","Blimpo",4);
hasDMAmap("Mercator","BuffaloKeys",5);
cout<<shirt<<endl;
cout<<balloon<<endl;
cout<<map<<endl;
lacksDMAballoon2(balloon);
hasDMAmap2;
map2=map;
cout<<balloon2<<endl;
cout<<map2<<endl;
ABC*pts[3];
pts[0]=&shirt;
pts[1]=&balloon;
pts[2]=&map;
for(inti=0;i<3;i++)
cout<<*pts[i]<<endl;
for(inti=0;i<3;i++)
pts[i]->View();
return0;
}
Chapter 14
PE 14-1

//pairs.h--defineaPairtemplate
#ifndefPAIRS_H_
#definePAIRS_H_
template<classT1,classT2>
classPair
{
private:
T1a;
T2b;
public:
T1&first();
T2&second();
T1first()const{returna;}
T2second()const{returnb;}
Pair(constT1&aval,constT2&bval):a(aval),b(bval){}
Pair(){}
};
#endif
//winec.h--wineclassusingcontainment
#ifndefWINEC_H_
#defineWINEC_H_
#include<iostream>
#include<string>
#include<valarray>
#include"pairs.h"
classWine
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 49 oI 65 September 2, 2004
{
private:
typedefstd::valarray<int>ArrayInt;
typedefPair<ArrayInt,ArrayInt>PairArray;
std::stringlabel;//winebrandname
intyears;//numberofyears
PairArraydata;
public:
Wine():label("none"),years(0),data(ArrayInt(),ArrayInt()){}
Wine(constchar*l,inty,constintyr[],constintbot[]);
Wine(constchar*l,constArrayInt&yr,constArrayInt&bot);
Wine(constchar*l,constPairArray&yr_bot);
Wine(constchar*l,inty);
voidGetBottles();
voidShow()const;
conststd::string&Label(){returnlabel;}
intsum()const{returndata.second().sum();}
};
#endif
//winec.cpp--Wineclasswithcontainment
#include<iostream>
#include"winec.h"
usingstd::cin;
usingstd::cout;
usingstd::cerr;
usingstd::endl;
Wine::Wine(constchar*l,inty,constintyr[],constintbot[])
:label(l),years(y),data(ArrayInt(yr,y),ArrayInt(bot,y))
{
}
Wine::Wine(constchar*l,constArrayInt&yr,constArrayInt&bot)
:label(l),years(yr.size()),data(ArrayInt(yr),ArrayInt(yr))
{
if(yr.size()!=bot.size())
{
cerr<<"Yeardata,bottledatamismatch,arraysetto0size.\n";
years=0;
data=PairArray(ArrayInt(),ArrayInt());
}
else
{
data.first()=yr;
data.second()=bot;
}
}
Wine::Wine(constchar*l,constPairArray&yr_bot)
:label(l),years(yr_bot.first().size()),data(yr_bot){}
Wine::Wine(constchar*l,inty):label(l),years(y),
data(ArrayInt(0,y),ArrayInt(0,y))
{}
voidWine::GetBottles()
{
if(years<1)
{
cout<<"Nospaceallocatedfordata\n";
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 50 oI 65 September 2, 2004
return;
}
cout<<"Enter"<<label<<
"datafor"<<years<<"year(s):\n";
for(inti=0;i<years;i++)
{
cout<<"Enteryear:";
cin>>data.first()[i];
cout<<"Enterbottlesforthatyear:";
cin>>data.second()[i];
}
}
voidWine::Show()const
{
cout<<"Wine:"<<label<<endl;
cout<<"\tYear\tBottles\n";
for(inti=0;i<years;i++)
cout<<'\t'<<data.first()[i]
<<'\t'<<data.second()[i]<<endl;
}
//pe14-1.cpp--usingWineclasswithcontainment
#include<iostream>
#include"winec.h"
intmain(void)
{
usingstd::cin;
usingstd::cout;
usingstd::endl;
cout<<"Enternameofwine:";
charlab[50];
cin.getline(lab,50);
cout<<"Enternumberofyears:";
intyrs;
cin>>yrs;
Wineholding(lab,yrs);//storelabel,years,givearraysyrselements
holding.GetBottles();//solicitinputforyear,bottlecount
holding.Show();//displayobjectcontents
constintYRS=3;
inty[YRS]={1993,1995,1998};
intb[YRS]={48,60,72};
//createnewobject,initializeusingdatainarraysyandb
Winemore("GushingGrapeRed",YRS,y,b);
more.Show();
cout<<"Totalbottlesfor"<<more.Label()//useLabel()method
<<":"<<more.sum()<<endl;//usesum()method
cout<<"Bye\n";
return0;
}
PE14- 2
//pairs.h--defineaPairtemplate
#ifndefPAIRS_H_
#definePAIRS_H_
template<classT1,classT2>
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 51 oI 65 September 2, 2004
classPair
{
private:
T1a;
T2b;
public:
T1&first();
T2&second();
T1first()const{returna;}
T2second()const{returnb;}
Pair(constT1&aval,constT2&bval):a(aval),b(bval){}
Pair(){}
};
#endif
//winei.h--wineclassusingprivateinheritance
#ifndefWINEC_H_
#defineWINEC_H_
#include<iostream>
#include<string>
#include<valarray>
#include"pairs.h"
classWine:privatestd::string,
privatePair<std::valarray<int>,std::valarray<int>>
{
private:
typedefstd::valarray<int>ArrayInt;
typedefPair<ArrayInt,ArrayInt>PairArray;
intyears;//numberofyears
public:
Wine():std::string("none"),years(0),PairArray(ArrayInt(),
ArrayInt()){}
Wine(constchar*l,inty,constintyr[],constintbot[]);
Wine(constchar*l,constArrayInt&yr,constArrayInt&bot);
Wine(constchar*l,constPairArray&yr_bot);
Wine(constchar*l,inty);
voidGetBottles();
voidShow()const;
conststd::string&Label()const{return(conststd::string&)(*this);}
intsum()const{returnPairArray::second().sum();}
};
#endif
//winei.cpp--Wineclasswithprivateinheritance
#include<iostream>
#include"winei.h"
usingstd::cin;
usingstd::cout;
usingstd::cerr;
usingstd::endl;
usingstd::string;
Wine::Wine(constchar*l,inty,constintyr[],constintbot[])
:string(l),years(y),PairArray(ArrayInt(yr,y),ArrayInt(bot,y))
{
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 52 oI 65 September 2, 2004
Wine::Wine(constchar*l,constArrayInt&yr,constArrayInt&bot)
:string(l),years(yr.size()),PairArray(ArrayInt(yr),ArrayInt(yr))
{
if(yr.size()!=bot.size())
{
cerr<<"Yeardata,bottledatamismatch,arraysetto0size.\n";
years=0;
PairArray::operator=(PairArray(ArrayInt(),ArrayInt()));
}
else
{
PairArray::first()=yr;
PairArray::second()=bot;
}
}
Wine::Wine(constchar*l,constPairArray&yr_bot)
:string(l),years(yr_bot.first().size()),PairArray(yr_bot){}
Wine::Wine(constchar*l,inty):string(l),years(y),
PairArray(ArrayInt(0,y),ArrayInt(0,y))
{}
voidWine::GetBottles()
{
if(years<1)
{
cout<<"Nospaceallocatedfordata\n";
return;
}
cout<<"Enter"<<Label()<<
"datafor"<<years<<"year(s):\n";
for(inti=0;i<years;i++)
{
cout<<"Enteryear:";
cin>>PairArray::first()[i];
cout<<"Enterbottlesforthatyear:";
cin>>PairArray::second()[i];
}
}
voidWine::Show()const
{
cout<<"Wine:"<<Label()<<endl;
cout<<"\tYear\tBottles\n";
for(inti=0;i<years;i++)
cout<<'\t'<<PairArray::first()[i]
<<'\t'<<PairArray::second()[i]<<endl;
}
//pe14-2.cpp--usingWineclasswithprivateinheritance
#include<iostream>
#include"winei.h"
intmain(void)
{
usingstd::cin;
usingstd::cout;
usingstd::endl;
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 53 oI 65 September 2, 2004
cout<<"Enternameofwine:";
charlab[50];
cin.getline(lab,50);
cout<<"Enternumberofyears:";
intyrs;
cin>>yrs;
Wineholding(lab,yrs);//storelabel,years,givearraysyrselements
holding.GetBottles();//solicitinputforyear,bottlecount
holding.Show();//displayobjectcontents
constintYRS=3;
inty[YRS]={1993,1995,1998};
intb[YRS]={48,60,72};
//createnewobject,initializeusingdatainarraysyandb
Winemore("GushingGrapeRed",YRS,y,b);
more.Show();
cout<<"Totalbottlesfor"<<more.Label()//useLabel()method
<<":"<<more.sum()<<endl;//usesum()method
cout<<"Bye\n";
return0;
}
PE 14-4

//pe14-pg.h
#include<iostream>
#include<cstring>
#include<cstdlib>
constintLen=20;
classPerson
{
private:
charfname[Len];
charlname[Len];
public:
Person(){fname[0]=lname[0]='\0';}
Person(constchar*fn,constchar*ln);
virtual~Person(){}
virtualvoidshow()const{std::cout<<fname<<""<<lname;}
virtualvoidset();
};
classGunslinger:virtualpublicPerson
{
private:
doubledrawtime;
intnotches;
public:
Gunslinger():Person("Joe","Doe"),drawtime(0.0),
notches(0){}
Gunslinger(constchar*fn,constchar*ln,
doubled=1.0,intn=0):Person(fn,ln),
drawtime(d),notches(n){}
Gunslinger(constPerson&p,doubled=1.0,intn=0):
Person(p),drawtime(d),notches(n){}
virtual~Gunslinger(){}
//Person(p)isthedefaultcopyconstructor
doubledraw(){returndrawtime;}
voidshow()const;
voidset();
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 54 oI 65 September 2, 2004
};
classPokerPlayer:virtualpublicPerson
{
public:
PokerPlayer():Person("Busted","Strait"){}
PokerPlayer(constchar*fn,constchar*ln):Person(fn,ln){}
PokerPlayer(constPerson&p):Person(p){}
virtual~PokerPlayer(){}
intdraw()const{returnstd::rand()%52+1;}
};
classBadDude:publicGunslinger,publicPokerPlayer
{
public:
BadDude():Person("Bad","Dude"),Gunslinger(){}
BadDude(constchar*fn,constchar*ln,
doubled=1.0,intn=0):Person(fn,ln),
Gunslinger(fn,ln,d,n){}
BadDude(constPerson&p,doubled=1.0,intn=0):
Person(p),Gunslinger(p,d,n){}
doublegdraw()const{returnGunslinger::draw();}
intcdraw()const{returnPokerPlayer::draw();}
voidshow()const{Gunslinger::show();}
voidset(){Gunslinger::set();}
};
#include<iostream>
#include<cstring>
#include"pe14-4pg.h"
Person::Person(constchar*fn,constchar*ln)
{
std::strncpy(fname,fn,Len-1);
fname[Len-1]='\0';
std::strncpy(lname,ln,Len-1);
lname[Len-1]='\0';
}
voidPerson::set()
{
std::cout<<"Enterfirstname:";
std::cin.getline(fname,Len);
std::cout<<"Enterlastname:";
std::cin.getline(lname,Len);
}
voidGunslinger::set()
{
Person::set();
std::cout<<"Enterdrawtime:";
std::cin>>drawtime;
std::cout<<"Enternumberofnotches:";
std::cin>>notches;
}
voidGunslinger::show()const
{
Person::show();
std::cout<<":"<<drawtime<<"drawtime,"<<notches
<<"notches\n";
}
//pe14-4.cpp
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 55 oI 65 September 2, 2004
#include<iostream>
#include<cstring>
#include"pe14-4pg.h"
constintSIZE=5;
intmain(void)
{
usingnamespacestd;
intct,i;
Person*gang[SIZE];
for(ct=0;ct<SIZE;ct++)
{
charchoice;
cout<<"Enterthegangcategory:\n"
<<"o:ordinarypersong:gunslinger"
<<"p:pokerplayerb:baddudeq:quit\n";
cin>>choice;
while(strchr("ogpbq",choice)==NULL)
{
cout<<"Pleaseenterano,g,p,b,orq:";
cin>>choice;
}
if(choice=='q')
break;
switch(choice)
{
case'o':gang[ct]=newPerson;
break;
case'g':gang[ct]=newGunslinger;
break;
case'p':gang[ct]=newPokerPlayer;
break;
case'b':gang[ct]=newBadDude;
break;
}
cin.get();
gang[ct]->set();
}
cout<<"\nHereisyourgang:\n";
for(i=0;i<ct;i++)
{
cout<<'\n';
gang[i]->show();
}
for(i=0;i<ct;i++)
deletegang[i];
cout<<"\nBye!\n";
return0;
}
Chapter 15
PE 15-1

//pe15tv.h--TvandRemoteclasses
#ifndefPE15TV_H_
#definePE15TV_H_
classTv
{
public:
friendclassRemote;//RemotecanaccessTvprivateparts
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 56 oI 65 September 2, 2004
enumState{Off,On};
enum{MinVal,MaxVal=20};
enum{Antenna,Cable};
enum{TV,VCR};
Tv(States=Off,intmc=100):state(s),volume(5),
maxchannel(mc),channel(2),mode(Cable),input(TV){}
voidonoff(){state=(state==On)?Off:On;}
boolison(){returnstate==On?true:false;}
boolvolup();
boolvoldown();
voidchanup();
voidchandown();
voidset_mode(){mode=(mode==Antenna)?Cable:Antenna;}
voidset_input(){input=(input==TV)?VCR:TV;}
voidsettings();
voidrmode(Remote&r);
private:
Statestate;
intvolume;
intmaxchannel;
intchannel;
intmode;
intinput;
};
classRemote
{
friendclassTv;
public:
enumStyle{Normal,Interactive};
Remote(intm=Tv::TV,ints=Normal):
mode(m),style(s){}
boolvolup(Tv&t){returnt.volup();}
boolvoldown(Tv&t){returnt.voldown();}
voidonoff(Tv&t){t.onoff();}
voidchanup(Tv&t){t.chanup();}
voidchandown(Tv&t){t.chandown();}
voidset_chan(Tv&t,intc){t.channel=c;}
voidset_mode(Tv&t){t.set_mode();}
voidset_input(Tv&t){t.set_input();}
voidshow_style();
private:
intmode;//TVorVCR
intstyle;//NormalorInteractive
};
//placedefinitionherewherebothTvandRemote
//classdeclarationsareknown
inlinevoidTv::rmode(Remote&r)
{
if(state==Off)
return;
if(r.style==Remote::Normal)
r.style=Remote::Interactive;
elser.style=Remote::Normal;
}
#endif
//pe15tv.cpp
#include<iostream>
#include"pe15tv.h"
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 57 oI 65 September 2, 2004
boolTv::volup()
{
if(volume<MaxVal)
{
volume++;
returntrue;
}
else
returnfalse;
}
boolTv::voldown()
{
if(volume>MinVal)
{
volume--;
returntrue;
}
else
returnfalse;
}
voidTv::chanup()
{
if(channel<maxchannel)
channel++;
else
channel=1;
}
voidTv::chandown()
{
if(channel>1)
channel--;
else
channel=maxchannel;
}
voidTv::settings()
{
usingstd::cout;
cout<<"TVis"<<(state==Off?"Off\n":"On\n");
if(state==On)
{
cout<<"Volumesetting="<<volume<<"\n";
cout<<"Channelsetting="<<channel<<"\n";
cout<<"Mode="
<<(mode==Antenna?"antenna\n":"cable\n");
cout<<"Input="
<<(input==TV?"TV\n":"VCR\n");
}
}
voidRemote::show_style()
{
if(style==Normal)
std::cout<<"RemoteinNormalmode\n";
else
std::cout<<"RemoteinInteractivemode\n";
}
//pe15-1.cpp
//linkwithpe15tv.cpp
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 58 oI 65 September 2, 2004
#include<iostream>
#include"pe15tv.h"
intmain(void)
{
Tvs20;
std::cout<<"Initialsettingsfor20\"TV:\n";
s20.settings();
s20.onoff();
s20.chanup();
std::cout<<"\nAdjustedsettingsfor20\"TV:\n";
s20.settings();
Remotegrey;
grey.set_chan(s20,10);
grey.volup(s20);
grey.volup(s20);
std::cout<<"\n20\"settingsafterusingremote\n";
s20.settings();
Tvs27(Tv::On);
s27.set_mode();
grey.set_chan(s27,28);
std::cout<<"\n27\"settings:\n";
s27.settings();
grey.show_style();//checkmode
s27.rmode(grey);//changemode
grey.show_style();//recheckmode
s27.onoff();//turnsetoff
s27.rmode(grey);//trychangingmodeagain
grey.show_style();//checkresult
return0;
}
PE 15-2

//pe15-2.h--exceptionclassesforhmean(),gmean()
#ifndefPE15_2_H_
#definePE15_2_H_
#include<iostream>
#include<stdexcept>
classhmeanexcp:publicstd::logic_error
{
public:
hmeanexcp()
:std::logic_error("hmean()invalidarguments:a=-b\n")
{
}
};
classgmeanexcp:publicstd::logic_error
{
public:
gmeanexcp()
:std::logic_error("gmean()argumentsshouldbe>=0\n")
{
}
};
#endif
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 59 oI 65 September 2, 2004
//pe15-2.cpp
#include<iostream>
#include<cmath>//ormath.h,unixusersmayneed-lmflag
#include"pe15-2.h"
//functionprototypes
doublehmean(doublea,doubleb)throw(hmeanexcp);
doublegmean(doublea,doubleb)throw(gmeanexcp);
intmain()
{
usingstd::cout;
usingstd::cin;
usingstd::endl;
doublex,y,z;
cout<<"Entertwonumbers:";
while(cin>>x>>y)
{
try{//startoftryblock
z=hmean(x,y);
cout<<"Harmonicmeanof"<<x<<"and"<<y
<<"is"<<z<<endl;
cout<<"Geometricmeanof"<<x<<"and"<<y
<<"is"<<gmean(x,y)<<endl;
cout<<"Enternextsetofnumbers<qtoquit>:";
}//endoftryblock
catch(hmeanexcp&bg)//startofcatchblock
{
cout<<bg.what();
cout<<"Tryagain.\n";
continue;
}
catch(gmeanexcp&bh)
{
cout<<bh.what();
cout<<"Sorry,youdon'tgettoplayanymore.\n";
break;
}//endofcatchblock
}
cout<<"Bye!\n";
return0;
}
doublehmean(doublea,doubleb)throw(hmeanexcp)
{
if(a==-b)
throwhmeanexcp();
return2.0*a*b/(a+b);
}
doublegmean(doublea,doubleb)throw(gmeanexcp)
{
if(a<0||b<0)
throwgmeanexcp();
returnstd::sqrt(a*b);
}
Chapter 16
PE 16-1

Solutions Ior Programming Exercises in C Primer Plus, 5


th
Edition
SP 60 oI 65 September 2, 2004
//pe16-1.cpp--oneofmanypossiblesolutions
#include<iostream>
#include<string>
boolisPal(conststd::string&s);
intmain()
{
std::stringinput;
std::cout<<"Enterastring(emptystringtoquit):\n";
std::getline(std::cin,input);
while(std::cin&&input.size()>0)
{
if(isPal(input))
std::cout<<"Thatwasapalindrome!\n";
else
std::cout<<"Thatwasnotapalindrome!\n";
std::cout<<"Enterastring(emptystringtoquit):\n";
std::getline(std::cin,input);
}
std::cout<<"Bye!\n";
return0;
}
boolisPal(conststd::string&s)
{
std::stringrev(s.rbegin(),s.rend());//constructreversedstring
//someoldercompilersdontimplementtheaboveconstructor
//anotherapproachisthis
//std::stringrev(s);//revsamesizeass
//copy(s.rbegin(),s.rend(),rev.begin());
return(rev==s);
}
PE 16-4

//pe16-4.cpp--onepossibility
#include<iostream>
#include<algorithm>
#defineMAX10
intreduce(longar[],intn);
voidshow(constlongar[],intn);
intmain()
{
longmyarray[MAX]={12,12,5,6,11,5,6,77,11,12};
show(myarray,MAX);
intnewsize=reduce(myarray,MAX);
show(myarray,newsize);
return(0);
}
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 61 oI 65 September 2, 2004
intreduce(longar[],intn)
{
//oronecouldcopytoalistanduselistmethods
//orcopytoaset;ineithercase,copyresults
//backtoarray
std::sort(ar,ar+n);
long*past_end;
past_end=std::unique(ar,ar+n);
returnpast_end-ar;
}
voidshow(constlongar[],intn)
{
for(inti=0;i<n;i++)
std::cout<<ar[i]<<'';
std::cout<<std::endl;
}
PE 16-8

//pe16-8.cpp
#include<iostream>
#include<set>
#include<algorithm>
#include<iterator>
#include<cstdlib>
#include<string>
intmain()
{
usingnamespacestd;
stringtemp;
set<string>mats;
cout<<"EnterMat'sguestlist(emptylinetoquit):\n";
while(getline(cin,temp)&&temp.size()>0)
mats.insert(temp);
ostream_iterator<string,char>out(cout,"\n");
cout<<"Mat'sguestlist:\n";
copy(mats.begin(),mats.end(),out);
set<string>pats;
cout<<"EnterPat'sguestlist(emptylinetoquit):\n";
while(getline(cin,temp)&&temp.size()>0)
pats.insert(temp);
cout<<"\nPat'sguestlist:\n";
copy(pats.begin(),pats.end(),out);
set<string>both;
set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),
insert_iterator<set<string>>(both,both.begin()));
cout<<"\nMergedguestlist:\n";
copy(both.begin(),both.end(),out);
return0;
}
Chapter 17
PE 17-1
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 62 oI 65 September 2, 2004
//pe17-1.cpp
#include<iostream>
intmain(void)
{
usingnamespacestd;
charch;
intcount=0;
while(cin.get(ch)&&ch!='$')
count++;
if(ch=='$')
cin.putback(ch);
else
cout<<"Endofinputwasreached\n";
cout<<count<<"charactersread\n";
cin.get(ch);
cout<<"Thennextinputcharacteris"<<ch<<endl;
return0;
}
PE 17-3

//pe17-3.cpp
#include<iostream>
#include<fstream>
#include<cstdlib>
intmain(intargc,char*argv[])
{
usingnamespacestd;
if(argc<3)
{
cerr<<"Usage:"<<argv[0]
<<"source-filetarget-file\n";
exit(EXIT_FAILURE);
}
ifstreamfin(argv[1]);
if(!fin)
{
cerr<<"Can'topen"<<argv[1]<<"forinput\n";
exit(EXIT_FAILURE);
}
ofstreamfout(argv[2]);
if(!fout)
{
cerr<<"Can'topen"<<argv[2]<<"foroutput\n";
exit(EXIT_FAILURE);
}
charch;
while(fin.get(ch))
fout<<ch;
cout<<"Contentsof"<<argv[1]<<"copiedto"
<<argv[2]<<endl;
fin.close();
fout.close();
return0;
}
PE 17-5

Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 63 oI 65 September 2, 2004
//pe17-5.cpp
#include<iostream>
#include<fstream>
#include<set>
#include<algorithm>
#include<iterator>
#include<cstdlib>
#include<string>
intmain()
{
usingnamespacestd;
ifstreammat("mat.dat");
if(!mat.is_open())
{
cerr<<"Can'topenmat.dat.\n";
exit(1);
}
ifstreampat("pat.dat");
if(!pat.is_open())
{
cerr<<"Can'topenpat.dat.\n";
exit(1);
}
ofstreammatnpat("matnpat.dat");
if(!matnpat.is_open())
{
cerr<<"Can'topenpat.dat.\n";
exit(1);
}
stringtemp;
set<string>mats;
while(getline(mat,temp))
mats.insert(temp);
ostream_iterator<string,char>out(cout,"\n");
cout<<"Mat'sguestlist:\n";
copy(mats.begin(),mats.end(),out);
set<string>pats;
while(getline(pat,temp))
pats.insert(temp);
cout<<"\nPat'sguestlist:\n";
copy(pats.begin(),pats.end(),out);
ostream_iterator<string,char>fout(matnpat,"\n");
set<string>both;
set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),
insert_iterator<set<string>>(both,both.begin()));
cout<<"\nMergedguestlist:\n";
copy(both.begin(),both.end(),out);
copy(both.begin(),both.end(),fout);
return0;
}
if(!pat.is_open())
{
cerr<<"Can'topenpat.dat.\n";
exit(1);
}
ofstreammatnpat("matnpat.dat");
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 64 oI 65 September 2, 2004
if(!matnpat.is_open())
{
cerr<<"Can'topenpat.dat.\n";
exit(1);
}
stringtemp;
set<string>mats;
while(getline(mat,temp))
mats.insert(temp);
ostream_iterator<string,char>out(cout,"\n");
cout<<"Mat'sguestlist:\n";
copy(mats.begin(),mats.end(),out);
set<string>pats;
while(getline(pat,temp))
pats.insert(temp);
cout<<"\nPat'sguestlist:\n";
copy(pats.begin(),pats.end(),out);
ostream_iterator<string,char>fout(matnpat,"\n");
set<string>both;
set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),
insert_iterator<set<string>>(both,both.begin()));
cout<<"\nMergedguestlist:\n";
copy(both.begin(),both.end(),out);
copy(both.begin(),both.end(),fout);
return0;
}
PE 17-7

//pe17-7.cpp
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
voidShowStr(conststd::string&s);
voidGetStrs(std::istream&is,std::vector<std::string>&vs);
classStore
{
public:
std::ostream&os;
Store(std::ostream&o):os(o){}
voidoperator()(conststd::string&s);
};
intmain()
{
usingnamespacestd;
vector<string>vostr;
stringtemp;
//acquirestrings
cout<<"Enterstrings(emptylinetoquit):\n";
while(getline(cin,temp)&&temp[0]!='\0')
Solutions Ior Programming Exercises in C Primer Plus, 5
th
Edition
SP 65 oI 65 September 2, 2004
vostr.push_back(temp);
cout<<"Hereisyourinput.\n";
for_each(vostr.begin(),vostr.end(),ShowStr);
//storeinafile
ofstreamfout("strings.dat",ios_base::out|ios_base::binary);
for_each(vostr.begin(),vostr.end(),Store(fout));
fout.close();
//recoverfilecontents
vector<string>vistr;
ifstreamfin("strings.dat",ios_base::in|ios_base::binary);
if(!fin.is_open())
{
cerr<<"Couldnotopenfileforinput.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin,vistr);
cout<<"\nHerearethestringsreadfromthefile:\n";
for_each(vistr.begin(),vistr.end(),ShowStr);
return0;
}
voidShowStr(conststd::string&s)
{
std::cout<<s<<std::endl;
}
voidStore::operator()(conststd::string&s)
{
std::size_tlen=s.size();
os.write((char*)&len,sizeof(std::size_t));
os.write(s.data(),len);
}
voidGetStrs(std::istream&is,std::vector<std::string>&vs)
{
std::stringtemp;
size_tlen;
while(is.read((char*)&len,sizeof(size_t))&&len>0)
{
charch;
temp="";
for(intj=0;j<len;j++)
{
if(is.read(&ch,1))
{
temp+=ch;
}
else
break;
}
if(is)
vs.push_back(temp);
}
}

You might also like