c++ in one day: the ultimate beginners guide to c++ with 7 awesome projects
TRANSCRIPT
![Page 1: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/1.jpg)
![Page 2: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/2.jpg)
C++InOneDayTheUltimateBeginnersGuideToC++With7AwesomeProjects
ByW.BEan
![Page 3: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/3.jpg)
Copyright2016-AllRightsReserved–W.BEanALLRIGHTSRESERVED.Nopartofthispublicationmaybereproducedortransmittedinanyformwhatsoever,electronic,ormechanical,includingphotocopying,
recording,orbyanyinformationalstorageorretrievalsystemwithoutexpresswritten,datedandsignedpermissionfromtheauthor.
![Page 4: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/4.jpg)
INTRODUCTION:
Manytimeswewonderhowcomputerscanworkfromtheinside.Fortheenduser,thereispracticallynointeractionwithsomethingdeeper.Theydonotneedtoknowmanydetailsabouthowthecomputerworksorsomethingaboutprogramming.Theenduserisonlyattractedbythefunctionalityandtheprogramtohaveasimpleinterfacethatiseasytohandle.However,thesoftwaredoesnotcreatebyitself.Somebodyhastodothedirtywork.Or,likeotherliketocallit,theartofprogramming.Themainpartofcomputersistheirmicroprocessor,thebrainthatexecuteseveryinstructionneededforeverytasktheuserneeds.Theseprocessoronlyunderstandsbinarycode(zerosandones)anditdoesnotknownothingaboutEnglishornumbers.So,howcanweinteractwiththeprocessor?Weuseprogramminglanguages.Throughhistory,manylanguageshavebeendevelopedfortheinteractionbetweentheprogrammersandthemachines.Inrecenttimes,programminghasbecomeamajorfieldofstudywithawidevarietyofprogramminglanguagetochoosedependingonthepurpose.OneofthemostpreferredlanguagesisC++.Why?Mainlybecauseofitsspeed,itsstandardsandthewiderangeofapplications.C++wasdevelopedasanimprovementfortheCprogramminglanguage.Thischangeaddedmanyfeatures,likeenablingobjectorientedprogramming,templates,memoryhandling,errorhandlingandmoretoolsfortheprogrammers.TheC++inonedayCourseistargetedforpeoplewhowanttolearnthebasicsoftheC++programminglanguage.Wewillcoverfromthemostbasicconceptsandstuff,perfectforbeginners,andasthecoursegoes,wewillbeaddingmorefeaturesfromthelanguageandalsostarttodevelopsomereallifeprojects.Thiscourseisdividedinfoursections:
1.ThebasicsofC++:Inthischapter,wewillcoverthebasicsofC++.Thisisthemaincoreofthecourseforbeginners.HerewewillcoverthebasicstructureforeveryC++program.Abriefexplanationofthelibrarysystem.ThestandardsystemofinputandoutputfromC++.Datatypesareanotherfundamentaltopictocoverandwillbediscussed,includingexamplesof
![Page 5: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/5.jpg)
declaration,usingandstoringvalues.Stringprocessingwillbecovered.Inthischapter,wewillalsoexplainthebasicflowstructuresthatareusedinC++fordesigningsoftware.Theifstructure,theswitchstructure,thewhilestructureandtheforstructure.Finally,averybriefintroductiontothebasicsofobjectorientedprogramming.
2.ThingstodowithC++:Inthischapter,wewilldiscusswhatkindsofsoftwarecanbedevelopedusingtheC++programminglanguage.3.ImplementingprojectswithC++:Herewewillwritesomecode!7projectshavebeenselectedandprogrammedinordertoshowyouhowyoucandousefulthingswithC++.4.Whattodonext:Finally,wefinishthecoursewithsomerecommendationsontopicsthat,whilearenotverynecessaryforthebasics,theyareagoodplacetofollowafterlearningthebasics.Thesefeaturescanenableyoutodesignmoreoptimalandcomplexsoftware.
So,let’sgetstarted!
![Page 6: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/6.jpg)
CHAPTER1:BASICSOFC++C++isamultipurposeprogramminglanguage.Whatisthis?Thatitcanbeusedforwritingeverytypeofsoftwarethattheprogrammerwants.Itcanbefromasimpleprogramlikecomputingthesumoftwonumbersuptoafulloperatingsystem(forexample,Windows)andvideogames(PS3,PS4,XBOX).SomeadvantagesthatC++hasoveritscompetitors(likeC#orJava)are,infirstplace,itsspeed.WhenyouwriteaC++program,itiscompiledtoabinaryfilethatrunsalongwiththeoperatingsystem.Second,itisstandard.C++hasaverywelldefinedstandardfrombeginningtoendandthismeansthat,iftheprogrammerwritescodeinstandardC++,itcanbeportedtoothercompilerswithminimumorsmallchanges.However,noteverythingisassimpleasitssounds.AlthoughC++isveryfast,itisverydifficulttomasterduetothelibrariesthatithasandtheStandardTemplateLibrary(STL)thatwillbediscussedinlaterchapters.Butlet’sgetstartedwiththebasicsofthelanguage.InstructionsandcompilerThroughthearticlewewillbeusingtheGNUC++compiler,G++,alongwiththeIDECodeLite.AllofthecodewillbewritteninstandardC++.CodeLiteandthecompilercanbedownloadedfromhttp://downloads.codelite.org/LibrariesThefullextensionofC++haslibrariesformanypurposes:inputandoutput,math,memorymanagement,time,fileprocessing,stringprocessingandmanymorefeatures.However,whenwestarttocode,wemustdefinewhichoftheselibrarieswewanttouseinourprogram.Since2003,C++alsoimplementedafeaturenamednamespaces,whichareanotherwaytoorganizeallofthestuffinsidethelanguage.ThemainfunctionInC++,allprogramsmustcontainafunction(orapieceofcode)namedmain.Thepurposeofthisfunctionistoindicatethecompilerwherewilltheprogramstartitsexecution.InputandOutput(I/O)AlmosteveryprograminC++needsaninputandanoutput.Therearesomeexceptionstotherule,butnormally,thereisalwaysI/O.Theinputisallthedatathatentersthecomputer,likenumbers,words.Theoutputarethedatathatisshowedtothescreen(alsonamedconsole).ThelibraryusedinC++forthisoperationsisnamediostream.Insideiostream,therearetwoobjectsthatwewillbeusingtoreaddatafromthekeyboardandshowingdatatotheconsole:coutandcin.
![Page 7: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/7.jpg)
Beforeprogramminganything,inCodeLitewemustcreateanewproject.StepsforcreatinganewprojectinCodeLite:
Inthemainscreenyouwillseeabuttonwiththetext“NEW”.Clickit.Whenthenewwindowappears,selectontheleftsidetheoption“Console”andselect“Simpleexecutable(g++)”fromthelist.Ontherightpanelchooseanameforyourproject,forexample“Example1”.Inprojectpath,selectafolderinyourcomputerwhereyouwillsaveyourcode.Inthecompilersection,besuretohave“gnug++”selected.ClickOK
Afterdoingthis,gototheleftsideofyourscreenandwillfindafolderwiththenameyouselectedforyourproject.Openitandyouwillseeanotherfoldernamedsrc(abbreviationforsource).Insidesrc,therewillbeafilenamedmain.cpp.ThisisthefilewhereyouwillwriteyourC++code.TheexamplecodeforasimpleinputandoutputinC++isasfollowing:#include<iostream>usingnamespacestd;intmain()
{
cout<<"ThisismyfirstC++program";return0;
}
Asyoucanappreciate,thefirstlineweincludedthelibraryforI/O.Onthesecondline,usingnamespacestdwesaytoC++thatwewanttouseallofthefeaturesinsidetheselectedlibraries(likecout).Afterthis,wefindourmainfunction.Hereiswherealltheexecutionbegins.AllfunctionsinC++haceanopeningandclosingbracethatindicateswherethefunctionstartsandends.Insidemain,thereisthelinecout<<“ThisismyfirstC++program”;Thislinewilloutputeverythinginsidethedoublequotestotheconsole.Noticethatthislineendswithasemicolon.InC++,alltheinstructionsinsideablockofcodeendwithasemicolon(therearesomeexceptionsthatwillbecovered).Youcanseethatbetweenthecoutobjectandourtext,therearetwo<signs.Theyarenamedoverloadedoperatorsandtheyrepresentthedirectionwheretheinformationistraveling,inthiscasetheinformationisgoingoutsidethecomputer.Asyoumaythink,whenwewanttomakeaninputtotheprogram,wewillbeusingthe>>operators.Forexecutingtheprogram,gototheBuildmenuandselecttheoptionBuildandRunproject.Youwillseehowablackscreenappears.Thisistheconsoleandthisiswherewewillperformourinputandoutput.PausingtheexecutionIftheconsoleappearsandimmediatelycloses,don’tworry,itisnormal.Butweneedtoseetheoutput.Forthis,add:cin.get()Beforereturn0;DataTypesandvariablesWhenweworkwithaprogram,therearemanytypesofdatawecanuse.Forexample:numbers,text,and
![Page 8: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/8.jpg)
somespecialtypesofdata.AllofthesearecalledDataTypes.TheyareveryimportantinC++becauseitisthemainpointfordevelopinginputs.InC++wehave3categories:numeric,alphabeticandbinary.Inthenumericcategorywehave3typesofdata:
int–Representintegernumbersfloat–Representsnumberswith7decimalpositionsafterthepointdouble–Representsnumberswith15/16decimalpositionsafterthepoint
Therearemorespecificnumericdatatypesbutforthepurposesofthisarticle,thesethreeareenough.Forthealphabeticcategorywehavetwotypesofdata:
char–Storeonealphanumericdigitstring–Storeasequenceofalphanumericdigits
Andinthebinarycategory,thereisonlyonedatatype:bool–Storeatrueorfalse.ZeroorOne.
Thebooldatatypemaysoundveryuselessatfirstbutithasitshandyapplicationswhenprogrammingsomespecificroutines.But,whydoweneedallofthesetypes?Simple:InC++thereisaconceptnamedvariable.Avariablecanstoreinformationofanyofthesementionedtypes.Imagineavariablelikeaboxthatcanholdsomevalueforacertaintimeandyoucandoanyoperationwiththatvalue.InC++,beforeusingvariables,wemustdeclarethem.How?Likethis:<datatype><nameOfVariable>Let’smakeasimpleexample.Wewanttocalculatethesumoftwonumbers.Thesenumbersareinteger.So,inordertoaccomplishthis,wemustdeclarethreevariables,oneforeachnumberandanotheronefortheresult:intnumberA;intnumberB;intresult;Asyoucansee,foreachvariablewedefinedtheinttypeandafterthedatatype,thenameforthevariable.Youcannamethevariablesinthewaythatyouwant,butitisrecommendabletogivethemanamesimilartotheuseitwillhave.Nowthequestionis:Howcanweassingavalue?Weusetheequal=operator:numberA=10;numberB=5;result=numberA+numberB;Forthis,Iassigned10tonumberAand5tonumberB.Afterthat,weassignedthevalueofresulttothesumofbothvariables.Thecompleteprogramwouldlooklikethis:#include<iostream>usingnamespacestd;intmain()
{
intnumberA;intnumberB;intresult;numberA=10;
![Page 9: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/9.jpg)
numberB=5;result=numberA+numberB;cout<<result;cin.get();return0;
}
Noticethathere,weusedcout<<result;forouroutputwithoutthedoublequotes.Whenyouusedoublequoutes,ALLthetextinsidethequoteswillgodirectlytothescreen.However,whenwewanttodisplaythevalueofavariable,wemustwritethenameofthevariablewithoutquotes.C++thenwilllookforthevalueinsidethevariableandshowitonyourscreen.Therearesomelimitationstothiscode.Forexample:wehavetoassignvaluesdirectlyinsidethecodeforthesum.Theoptimalwaywouldbegivingtheusertheoptionforinputthevaluesintotheprogram.Thiscanbedonelikethis:#include<iostream>usingnamespacestd;intmain()
{
intnumberA;intnumberB;intresult;cout<<"Enterfirstvalue:";cin>>numberA;cout<<"Entersecondvalue:";cin>>numberB;result=numberA+numberB;cout<<"Thesumofbothvaluesis:"<<result;cin.get();return0;
}
Noticesomedifferencesinrelationtotheothercode.First,thedeclarationofthethreevariablesweneed.Afterthis,wetelltheusertoenterthefirstvalue.Wecanseehowcin>>numerAisused.Withthisline,wetellC++tocapturetheinputfromthekeyboardandthevalueassignittothevariablenumberA.ThesamefornumberB.Afterthis,theresultofthesumiscalculatedandissenttotheoutput.Noticehowinthelastoutput,theoverloadedoperationappearstwice.Thisisveryconvenientwewanttoshowmultiplevaluesinthesameline.
![Page 10: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/10.jpg)
Now,let’ssaywewanttoknowtheaverageofthesetwovalues.Wecanmodifytheresultlineinthefollowingway:result=(numberA+numberB)/2;Theparenthesisindicatesthatthemathematicaloperationsinsidetheparenthesiswillbedonefirstly.Afterthat,itwillcontinuewiththerestoftheexpression.However,wehaveaproblemwiththisline.SupposenumberAhasthevalueof5andnumberBhasavalueof6.Theresultwouldbe5.5.Noproblemhereuntil…wenoticethatresultisdeclaredasint.And,accordingtoourdatatypes,theintdatatypeisreservedonlyforinteger.So,whatshouldweuse?Wemustchangethedatatypeofresulttoeitherfloatordouble.doubleresult;Besidessumanddivition,therearemoremathoperatorstoperformoperations.Thesustractionisperformedwiththe“-“operator,theproductisperformedwiththe“*”operator.Andaspecialcaseisthe“%”operator,namedModulus.Themoduluswillreturntheleftoverofadivision.MorecomplexmathemathicaloperationscanbeperformedwithC++usingthe<complex>library.Porexample,power,squareroot,trigonometricalfunctions,andmore.
StringI/OThemanagementofstringinC++canbedonewiththelibrary<string>.Itincludestheobjectstringthatweneedtouse.Forexample,let’ssupposewewantaprogramtosaygoodbyetoanyone.Itwouldlooklikethis:#include<iostream>#include<string>usingnamespacestd;intmain()
{
stringname;cout<<"What'syourname?";cin>>name;cout<<"Goodbye"<<name;cin.get();return0;
}
Thefirstthingyoumaynoticeisthatweaddedthestringlibrary.Insidemain,justlikeanyvariable,wedeclarednameasstringtype.Afterthat,werequestedtheusertowritetheirnameandthenoutputthesentence“Goodbye”followedbythegivenname.Let’sseeanotherexample:#include<iostream>#include<string>usingnamespacestd;intmain()
{
![Page 11: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/11.jpg)
{
stringname;stringlastname;stringfullname;cout<<"What'syourname?";cin>>name;cout<<"Andyourlastname?";cin>>lastname;fullname=name+""+lastname;cout<<"Goodbye"<<fullname;cin.get();return0;
}
Inthiscode,Ideclaredacoupleofextrastrings.Wealsorequesttheusertheirlastname.Inprogramming,wecallconcatenatetotheactionofattachstrings.Inthisexample,weconcatenatename,anemptyspaceandlastnametoproduceauniquestringcontainingthefullname.Andthatstringissenttotheoutput.ScapeSequencesThisisanadditiontotheI/Otopic.InC++,therearespecialsequencesthatallowtheprogrammerabetterdistributionoftheinformationthatisdisplayed.Thesequencesare:
\n–Endofline\t–Insertionoftabularspace
Withthesetwosequences,youcandesignawelldistributedinterface.Lookattheexample:cout<<“Hereisaline\n”<<“Hereisanotherline\t”<<“Iamafteratabspace”;Thisisasimpleexampleofthesequencesandcanbeusedonlywiththecoutobject.ProgramFlowUpuntilthispoint.Wehavecoveredthetypesofdata,howtoshowinfotothescreenandcapturingdatafromthekeyboard.Now,averyimportantpartofC++aretheflowcontrolinstructions.Withthispart,youwillbeabletotakedecisionsandmakecomplexprograms.IfStructureTheifisaconditionalstructure.Likeitsownnamesays,ifsomethinghappens,thendothisthing.Thestructuregoesasfollow:if(condition)
{
//dosomething
}
![Page 12: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/12.jpg)
Theconditionisaexpressioninwhichtheresultwillbetrueorfalse.Therearesomeoperatorstoevaluatethecondition:
EQUALS(==):Willbetrueifbothvaluesarethesame.Example:a=bAND(&&):Willbetrueifallvaluesaretrue.OR(||):Willbetrueifanyofthevaluesaretrue.NOT(!):Willbetrueifthevalueisfalse.GREATER(A>B):WillbetrueifAisgreaterthanBLESS(A<B):WillbetrueifBisgreaterthanA.
Let’ssupposewemustevaluateifastudentapprovedornotacourse.Lookathefollowingcode:#include<iostream>usingnamespacestd;intmain()
{
intnote;cout<<"Enteryournote:";cin>>note;if(note>6)
{
cout<<"Congratulations.Youpassed!";}return0;
}
Weasktheuserfortheircoursenote.Iftheuserentersanumbergreaterthan6,thentheflowoftheprogramentersthecodeblocksurroundedbythebraces.Ifnot,itignoresthisblockandcontinuesitsexecution.NoticethattheIFinstructiondoesnotendwithsemicolon.Thisisbecauseitisfollowedbyablockofcode.But,whathappenswhenthenoteislessthansix?Weusetheelsekeyword.#include<iostream>usingnamespacestd;intmain()
{
![Page 13: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/13.jpg)
intnote;cout<<"Enteryournote:";cin>>note;if(note>6)
{
cout<<"Congratulations.Youpassed!";}else
{
cout<<"Sorry.Youdidnotpassed";}return0;
}
Thiscodeisexactlythesameasthelastonewithonedifference.Weaddedtheelsekeywordwithitsrespectiveblockofcode.First,theconditionnote>6isevaluated.Ifthisconditionistrue,thentheblockofcodenexttotheifwillbeexecutedandtheelseblockcodewillbeignored.Iftheconditionisfalse,thentheifblockcodewillbeignoredandtheelseblockcodewillbeexecuted.Wecanalsoaddmultipleconditionsintheifclause.Lookatthefollowingcode:if(note==10)
{
cout<<"Excellent!";
}
elseif(note>6&¬e<10)
{
cout<<"Congratulations.Youpassed";}else
{
cout<<"Sorry.Youdidnotapprove";}Weaddedsomethingcalledelseifanditallowstheprogrammertoaddmultipleconditionsonthesameif.Inthisexample,ifnoteequalstoten,onlythefirstblockofcodeisgoingtobeexecuted.Onthesecondcontidion,ifnoteisgreaterthansixANDnoteislessthan10,thenthemiddleblockofcodewillbe
![Page 14: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/14.jpg)
executed.Youcanaddasmanyelseifasyoumaywantorneed.However,ifneithertheIFnoranyoftheELSEIFconditionsaretrue,thentheELSEblockofcodewillbeexecuted.TheelseisonlyexecutedwhennoneoftheIForELSEIFaretrue.MakingeasiermultipleconditionsYoumightthink“Hey,whatifIhavealotofconditions,like20or30?Itwillbealotofcode”andyes,youareright.Itwoulddefinitelybealotofhardworkhavingmanyconditions.ButC++hasaanswerforthis:theswitchinstruction.Withswitch,wecanusemultipleconditionsinasimpleway.Continuingthesameexampleofthenotes,let’ssupposewewantadifferentmessagefortheapprovingnotes.Startingfromsix,therewillbe5differentmessagesforapprovingandasinglemessageforfailing.Usingtheswitchstatement,thecodewouldlooklikethis:switch(note)
{
case10:cout<<"Excellent";break;case9:cout<<"Verygoodnote";break;case8:cout<<"Goodjob!";break;case7:cout<<"Notbad.Keepworking";break;case6:cout<<"Youpassedbyabit";break;default:cout<<"Youdidnotapprove";}Thefirstthingtowatchisthatthevariablewewanttocomparegoesinsidecurlybracesnexttotheswitchstatement.Itdoesnotneedtoendwithsemicolonbecauseitisfollowedbytheblockofcodefortheswitch.Foreachcomparison,weusethecasekeywordfollowedbythevaluewearelooking.Incasenotehasavalueof10,themessage“Excellent”goestotheoutput.Foreachcase,wemustaddthebreakkeyword.Ifwedonotdothis,theswitchstatementwillfalltothenextcaseuntileitherfindsabreakortheendoftheswitchcodeblock.LoopsAlright,soyounowknowhowtotakedecisionsonyourprogram.Youcandirecttheflowtoanotherpiecesofcodeanddecidewhichoneexecuteandwhen.Excellent.Let’ssaythatyouwanttocalculateanaverage.Eachstudentistaking5subjectsandyouwanttoknowtheaverageofthosenote.Simple,yousumthemupanddivideby5.But,thereisnotonestudentontheschool.Canyoucopythecodeandrepeatthis10or15times?Well..yes,youcoulddoit,butthecodewouldstartbeingveryunmanageable.So,howcanwefixthisproblem?C++hastherighttoolforthejob,anditiscalledloops.Aloopisablockofcodethatwillrepeatitselfuntilaconditionissatisfied.Wehavetwokindsofloops:countingloopsandconditionalloops.Thefirstoneiscalledforanditisusedwhenwealreadyknowhowmanytimeswewanttorepeattheblockofcode.Thesyntaxfortheforloopislikethis:for(VARIABLES;CONTIDION;INCREMENT)
![Page 15: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/15.jpg)
{
//Repeatsomecode
}
Thesecondisnamedwhile,anditwillloopuntilsomeconditionissatisfied.Thesyntaxlookslikethis:while(CONDITION)
{
//Repeatsomecode
}
Followingtheexampleoftheaverages,calculatingtheaveragefor10studentswilllooklikethis:floatnote1,note2,note3,note4,note5;floatavg;for(inti=0;i!=10;i++)
{
cout<<"Firstnote:";cin>>note1;cout<<"Secondnote:";cin>>note2;cout<<"Thirdnote:";cin>>note3;cout<<"Fourthnote:";cin>>note4;cout<<"Fifthnote:";cin>>note5;avg=(note1+note2+note3+note4+note5)/5;cout<<"Average:"<<avg<<"\n";}Asyoucansee,wedeclaredthevariablethatwearegoingtouseoutsidetheloop.Afterthis,wedeclaredavariablenamedi.Iisthecounteranditwillbeincrementedeveryloop.Lookatthedeclaration:itstartsatzero.Ontheconditionsection,theoperator“!=”meansdifferent,so,theloopcontinuewhileuntilIequalsto10(thatmeans,10times).Afterthis,gototheblockofcode.Theprogramaskstheusertoenterfivenotes.Don’tworryaboutcoutandcinonthesameline,thatistheuseofthesemicolon,separatingsentences.Afterthefivenotesareinside,theaverageiscalculatedandshowntothedisplay.Whenwereachtheendoftheblockthecode,wegobacktotheincrementandInowequalstoI+1.The++operatormeansthatthevariableisincrementedbyone.Withthispieceofcode,wecanruntheloopfor10times.But,let’ssaywewanttotelltheloophowmanystudentsareontheschool,notjustanantiquated10-times-run.Itcouldbethisway:intlimit;cout<<"Howmanystudentsareinyourschool?:";cin>>limit;for(inti=0;i!=limit;i++)
![Page 16: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/16.jpg)
{...}
Here,wedeclaredanothervariablenamedlimit.ThatnumberisobtainedfromthekeyboardandtheloopwillcontinueuntilIequalstolimit.Asyoumightobserve,wemustalwaysknowwhentheloopisgoingtoend(either10oravariable).But,howwedowhenwedonotknowhowtostop?Thisisasituationwhenthewhileloopisveryuseful.Let’ssayyouwanttocalculatetheaverageBUTyoudonotknowhowmanysubjectstheschoolhas.Justkeeptheprogramrunninguntilyoutolditto.Thiscouldbeaveryrealsituation.Andwecannotaskthestudent.So,lookatthispiece:intval=1;while(val==1)
{
cout<<"Firstnote:";cin>>note1;cout<<"Secondnote:";cin>>note2;cout<<"Thirdnote:";cin>>note3;cout<<"Fourthnote:";cin>>note4;cout<<"Fifthnote:";cin>>note5;avg=(note1+note2+note3+note4+note5)/5;cout<<"Average:"<<avg<<"\n";cout<<"Doyouwanttocontinue?[1]YES.[Other]NO";cin>>val;
}
Thiswouldbereadasfollow:“Whilevalueisequaltoone,executethiscode”.Whendoesvalchangesitsvalue?Attheendoftheblockofcode,whereweasktheuserifhewantstocontinueornot.Ifheselectsone,valcontinueshavingaone.Anythingelsewillresultontheterminationoftheloop.InfiniteloopsandexitsSometimesit’sveryusefultohaveinfiniteloops.Thiswillnotbemuchcoveredbutitisgoodtoknowhow.Inthewhileloop,its:While(true)
{
//Dosomething
}
Fortheloopfor:for(;;)
{
//Dosomething
![Page 17: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/17.jpg)
}
Thekeywordusedforendingtheloopsisbreak(yes,theonefromswitch).Itcanbeusedlikethis:while(true)
{
if(somethingHappens)
{
break;
}
}
StructuredDataandObjectOrientedProgrammingUpuntilthispoint,allthevariableswehaveusedaresingle,thedonotrepresentmuchofstuff,justavalue.Butinprogramming,therearecertainprogramsthatneedtobesolvedinadifferentwayofthinking.Thisiswhereobjectorientedprogrammingbeginsitsexistence.Youmayhavealreadyheardofthis.Intheprogrammingwehaveseen,doyouimagenhowcanyourepresentabook?Apen?ACar?Howcantheyinteractbetweenthemselves?It’sdifficult.So,Iwillintroduceyoutotheclass.Aclassisadesign(ortemplate)ofsomethingthatexistsinreallife.Don’tworry,it’sbuildwiththesamedatatypeswehaveseen.First,wewillrepresentaclassfromabook:classBook
{
public:stringtitle;stringauthor;intyear;intpages;
};
Thefirstthingisthewordclassfollowedbythenameofthethingwewanttodescribe.Insidethebraces,therewillbethepropertiesoftheclass.Why?Let’sputisinthisway:Whatdatacanweobtainfromthebook?Well,itstitle,theauthor,inwhatyearwaspublished,howmanypagesdoesithas.Noticehoweachpropertyhasitsowndatatype.Stringfortitleandauthor(becausetheyarecharacters)andintegerforyearandpages.Aftertheendoftheclass,DONOTFORGETTHESEMICOLON.
![Page 18: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/18.jpg)
Now,let’sputittogetherinasampleprogram:#include<iostream>#include<string>usingnamespacestd;classBook
{
public:stringtitle;stringauthor;intyear;intpages;
};
intmain()
{
BookmyFavoriteBook;BookmyLeastFavBook;myFavoriteBook.title="BeginningC++";myLeastFavBook.title="Idontremember";cout<<"Myfavoritebookis"<<myFavoriteBook.title<<"\n";cout<<"Ireallydontlike"<<myLeastFavBook.title<<"\n";cin.get();return0;
}
![Page 19: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/19.jpg)
Here,wedeclareourfavoritetypeasadatatypeBOOK.Afterthis,wecanaccessthemembersofthatobjectusingthe“.”operator.Afterthepoint,wehaveaccesstoallthepropertiesfromtheobject.Although
bothbooksarefromthesameBOOKclass,eachonehasitsownseparatedsetofproperties.
![Page 20: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/20.jpg)
CHAPTER2:TYPESOFTHINGSTOBUILDWITHC++
TherearemanykindsofthingstobuildusingC++.Asmentionedbefore,C++iswellpreferredforitsefficiencyandspeedofexecution.C++isamultipurposeprogramminglanguage.Thatmeansthatitcanbeusedtoprogramliterallyeverything.Thereareotherlanguagesthatare“purposespecific”,forexample,theRprogramminglanguageisforstatistics,orMATLAB,thatisusedformathandmatrixes.ThekindofthingsthatcanbebuiltusingC++literallydependsontheimaginationandcreativityoftheprogrammer.Herewewilllistsomeofthem.SecurityThinkforamomentfortheantivirusyouhaveinstalled(andifyoudon’thaveanyinstalled,anywaythinkofit).Itmustbeveryfastforsearchingandinspectingfiles(atbinarylevel),havefirewalls,internetconnectivityandagoodcommunicationwiththeoperatingsystem.TheonlylanguagethatcanmeettheserequirementsisC/C++.ThefeaturesofC/C++enablestheprogrammertoprogramatlowlevel(binaryandassembly)forthemostcomplicatedworkandalsoworkatthehighlevel(theAPIsusedtocommunicatetoWindows).VideogamesYes,C++maybeoneofthemost(orprobablythemost)preferredlanguagestowritevideogames.Itsspeedatperformingmathematicaloperationsgivesitaprettyniceadvantageoveritscompetitors.TherunnerupisC#.Andnotonlyvideogames,alsosomebackenginemotorsareprogrammedinC++,likeUnrealEngine.ItisdevelopedalmostallinC++(therestinassembly).And,Ibelievethatthisoneisevenharderbecause,ifyouhavealittleknowledgeonvideogamedevelopment,UnrealEngineisusedforcreatingvideogames.Examplesofthemare:TomClancyRanbowSixVegas,GearsofWar2&3&4,DeadIsland2,MassEffect2,BioShock,Assassin’sCreedChroniclesTrilogyandIamonlymentioningthefamousones.AndthesearemadeusingUnrealEngine.OperatingSystemsThisoneisveryhardtoexplain.Imagineafulloperatingsystem:booting,libraries,peripherals,APIs,memorymanagement,filesystem,commandline,
![Page 21: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/21.jpg)
andgraphicaluserinterface,everythingyouneed.Obviously,someofthelowestpartsofanoperatingsystemcannotturnthebacktoassemblylanguage,buttherestcanbemanagedusingonlyC++.Examples:well,Windows95,98,2000andXP.Apparently,WindowsVistahadbothC#andC++andthatwassomeofthereasonsofitspooreffiency,afterthat,MicrosoftusedcompletelyC#.Anotherone:MacOSX.AnotherprogramminglanguageItsoundkindofstrange.Youmightthink“HowcananotherlanguagebemadeusingC++?”Wellyes,itcanbedone.ItisnoteasybutindeedcanbeaccomplishedwithsomeprogrammingskillsandsomeofCompilersTheory.GuesswhatlanguagewasmadeusingC++?Java.Beingalittlebitmoretechnic,theJavaVirtualMachine(theboxthatexecuteseverythingJavaneedregardlesstheoperatingsystem)wasmadeusingC.But,C++inheritsallofthefeaturesofCplusitsownSTL,memorymanagementandmanymoretools.Thesamestorygoestopython.Pythonisaninterpretedprogramminglanguageandnotacompilationprogramminglanguage.Whatthismeansisthatthecodeisexecutedbyaninterpreter,ratherthantheoperatingsystem.Inpythontherearenoexecutables,onlyscripts.ButIwillletyouguessinwhatlanguagewaswrittentheinterpreter?Yes,that’sright.Inconclussion,youcandevelopwhatevercomestomindusingC++,it'sjustamatterofcreativity.
![Page 22: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/22.jpg)
CHAPTER3:PROJECT#1CALCULATOR
ThisprojectwillfocusontheuseofthemathtoolsthatC++hasforperformingmathcalculations.Lookatthiscode:#include<iostream>#include<cmath>usingnamespacestd;Here we define our headers. The <cmath> header is the one that has thefunctions thatC++usesfor themathoperations.It isanoriginalClibrary thatcanbeusedalongwithC++.Ourcalculatorwillhavefourkindsofoperations:arithmetical,trigonometrical,exponentialandlogarithmic.Inourmainfunctionwe’llhavesomethinglikethis:intmain()
{
intsel=0;cout << "ADVANCED CALCULATOR\n"; cout << "ENTER THE TYPE OFOPERATION YOUWANT TO CALCULATE\n"; cout << "[1] Arithmetic\n";cout << "[2] Trigonometric\n"; cout << "[3] Exponential\n"; cout << "[4]Logarithmic\n";cout<<"Yourchoice:";cin>>sel;switch(sel)
{
![Page 23: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/23.jpg)
case1:arithmetic();break;case2:trigonometric();break;case3:exponential();break;case4:logarithmic();break;default:cout<<"invalidoperation";}return0;
}
Herewedefineourmenufortheusertoselectthekindofoperationitwantstoperform.Thisoperationisstoredintheselvariable.Afterthis,wetelltheuserthedifferentkindsofoperationalongwiththevaluethatmustbeentered.Thevalueforselwillbeusedtocontroltheflowoftheprogramascanbeseen
![Page 24: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/24.jpg)
on the switch statement. Only applies for values between 1 and 4. Withsomethingdifferentthanthistheprogramwillend.voidarithmetic()
{
intop=0;floatA=0;floatB=0;cout << "Select operation\n"; cout << "[1] Addition\n"; cout << "[2]Substraction\n";cout<<"[3]Product\n";cout<<"[4]Division\n";cin>>op;cout<<"Enterfirstnumber:";cin>>A;cout<<"Entersecondnumber:";cin>>B;cout<<"Result:";switch(op)
{
case1:cout<<(A+B);break;case2:cout<<(A-B);break;
![Page 25: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/25.jpg)
case3:cout<<(A*B);break;case4:cout<<(A/B);break;default:cout<<"Invalidoperation";break;
}
cout<<endl;
}
In the arithmetic function, we request another time the user what kind ofoperationwants to perform,This section is only for the four basic operations.Heretheuserentersthekindofoperationandbothoperators.Aftertheprogramknows this data, it can perform the opration and show it to the screen.At theend,thecontrolflowreturntomain.voidtrigonometric()
{
![Page 26: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/26.jpg)
intop=0;floatval=0.0;cout << "Select\n"; cout << "[1] Sine\n"; cout << "[2] Cosine\n"; cout <<"Op:";cin>>op;cout<<"Entervalue:";cin>>val;if(op==1)
{
cout<<sin(val);
}
elseif(op==2)
{
cout<<cos(val);
}
else
{
![Page 27: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/27.jpg)
cout<<"Invalidoperation";}cout<<endl;
}
Withthetrigonometricalpart,isalmostthesame,butheretheusercancalculatethesineandcosinefunctions.Theusergives thevalueand theprogramreturntheresult.voidexponential()
{
floatbase=0.0;floateee=0.0;cout<<"Enterbase:";cin>>base;cout<<"Enterexpnent:";cin>>eee;cout<<pow(base,eee)<<endl;}Theexponentialpartcalculatesanyoperationfromx^n.Heretheuserentersthebaseandthepowerand,C++,usingthepow()functions,calculatesthevalueanddisplaysit.voidlogarithmic()
{
![Page 28: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/28.jpg)
floatvalue=0.0;cout<<"Entervalueforcalculatethelog(e):";cin>>value;cout<<log(value)<<endl;}Logarithmic section is almost the same but calculates the same but here, itcalculatestlee-basedlogarithmofthedatathattheuserinputstotheprogram.
![Page 29: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/29.jpg)
CHAPTER4:PROJECT#2:AGENDA
Forthisproject,wewillsimulateaphoneagenda,liketheoneyouhaveinyourhouseandusethemtokeeprecordofalltheimportantnumbersyouneed,butwewilldoitusingC++.Foreachcontact,theirnameandtheirphonewillbestored(althoughyoucanaddasmanyfieldsasyouwant).Also,wewillbeusinganewandverypowerfulfeatureoftheStandardTemplateLibraryofC++:vector.
Usingvectors
Imaginethisphoneagendawillhavemorethan100phonenumbers.Areyougoingtodeclare100variablesforthenumbers?Andanother100forthenames?Ofcoursenot.Hereiswherevectorfitsperfectly.Withvector,youwillbeabletoinsertasmanyelementsasyoulike.ForusingvectorinsideC++,wemustaddthelibrary<vector>inourcode.Wewillalsoneediostreamandstring.
So,ourlibrarieswillbe:
#include<iostream>
#include<string>
#include<vector>
usingnamespacestd;
Afterthenamespacestd,wearegoingtodeclareourvector.Thewillgooutsidethemainfunction.Bydeclaringanyvariableoutsidemain(oranyfunction)it
![Page 30: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/30.jpg)
meansthatthisvariablewillbeglobal.Inotherterms,anyonehasaccesstothemforreadingandwriting.Lookcloselyatthesyntax:
vector<string>Names;
vector<string>Phones;
Thewordvectorobviouslysaysthatthesevariableswillbevectors,butnow,lookinsidethesigns.
Thereisthewordstring.Withthis,wetellC++thatourvectorswillcontainonlystrings.Wecanonlyhavevectorsofints,ofstring,orany.Youcannotmixdatatypesinasinglevector.Now,wewillwriteourmainfunction.Duetothenatureofourprogram,weneedtobeabletonavigatethroughitssections.Theprogramwillhavethreesections:addacontact,searchforacontactusingitsIDandsearchforacontactusingtheirname.Foraccomplishthis,wewilluseamenuthatwillgiveusthesethreeoptionsandalsoanexitfromtheprogram.
Themainfunctionwouldlikethefollowingcode:intmain()
{
intsel=0;
while(true)
{
![Page 31: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/31.jpg)
cout<<"MyAgenda++\n\n";
cout<<"Chooseanumbertoexecuteanoption\n\n";cout<<"[1]NewContact\n";
cout<<"[2]SearchbyID\n";
cout<<"[3]SearchbyName\n";cout<<"[4]Exit\n";
cout<<"Yourchoice:";
cin>>sel;
switch(sel)
{
case1:
case2:
NewContact();
break;
![Page 32: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/32.jpg)
SearchByID();
break;
SearchByName();
break;
case3:
}
if(sel==4)
{
break;
}
}
![Page 33: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/33.jpg)
return0;
}
Weonlydeclaredasinglevariable,namedsel.Sel(forselection)willbeusedforthechoicethattheuserselectsatthemenu.Afterthedeclaration,youcanseehowwedeclaredaninfiniteloopusingwhile(true).Whydoweneedanendlessloop?Becausetheprogramwillcontinueitsexecutionuntil..well,wedon’tknow.Insideourloop,therearethecoutlines.Inhere,weshowalittletitletotheuser,“Agenda++”followedbytwolinejumps.Andthefourfollowingcoutsareusedfortellingtheuserthattherearefourdifferentchoicesintheprogram.Byselectinganyoneofthese,theprogramwillknowwheretogo.Nexttothis,welefttheprogramtotheuser,wherehewillintroduceitsselections.
Thatselectionfallsintotheswitchstatement.Iftheuserselects1,theprogramwillgointotheNewContact()function.
FunctionsInC++areawayofmodelingtheprogram.Notallthecodeiswritteninsidethemainfunctionbecauseitwouldbeverydifficulttofollowandalsotoimaginehowallofthepieceofcodeconnectthemselves.Instead,wedividetheprogramintosmallmodules,whereeachonetakescareofasingletask.
Importantnote:Inthecode,themainfunctionmustbethelastfunction.Writeallofthefollowingfunctionsinlinesbeforemain.
Inthisexample,thefunctionNewContact()hasthejobtorequesttheusertogiveanewnameandanewphone,likethis:voidNewContact()
{
stringname;
![Page 34: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/34.jpg)
stringphone;
cout<<"\n\nEnteranameforthecontact:";cin>>name;
cout<<"Enterthephoneforthiscontact:";cin>>phone;
cout<<"TheIDforthiscontactwillbe"<<Names.size()<<"\n\n";
Names.push_back(name);
Phones.push_back(phone);
}
Lookhowthefunctionstarts,itisverysimilartothemainfunction.Thewordvoidmeansthatthisfunctiondoesnotreturnanything(rightnowmaysoundconfusing,butyou’llgetitsoon).Afterthebraceiswherethefunctioncodeactuallystarts.Thefirstthingwedoistodeclareacoupleofstring,onenamednameandtheotheronephone.Thesestringwillbeusedfortheinputfromtheuser.
Werequesttheusertoenterthenameandthephoneforthenewcontact.Nowthatwehaveit,wemustassingthiscontactitsIDnumber.Rememberclasses?Thevectorcontainsapropertynamedsize(),whichtellsushowmanyelementsdoesthevectorholds.Inthiscase,weassigntheIDasthecurrentsize.
Afterthat,weuseanothergreattoolfromvector,actuallythemostbasicone:pushback.Imagineavectorlikeadeckofcards.Thefunctionpushbackwilladdanewelementatthebackoftheactualdeck.
![Page 35: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/35.jpg)
Forthisexample,weaddattheendofournamevectorthevaluethattheuserentered.Thesamethingforthethephones.Andnowwehavebothvaluesinourvectors.
Nowthatwehaveourfunctionforinsertingvalues,weneedtoretrievethemfromtheirstorage.
Thatiswherethefunctionsforsearchwillbeimplemented.Asmentionedbefore,wewillusetwotypesforsearchingvalues:oneusingtheIDofthecontactandtheotheroneusingthename.
FortheID,ourfunctionwillbelikethis:voidSearchByID()
{
intvalue;
cout<<"\n\nEntertheIDofthecontacttosearch:";cin>>value;
if(value>=Names.size())
{
cout<<"ThisIDdoesnotexist\n\n";return;
![Page 36: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/36.jpg)
}
cout<<"Informationforcontact"<<value<<"\n";cout<<"Name:"<<Names[value]<<"\n";cout<<"Phone:"<<Phones[value]<<"\n";}
Again,firstoffeverything,wewritethefunctionname,inthiscasewillbeSearchByID.Afterthis,thevariablevaluewillcontainthevaluethattheuserwantstosearch.Beforemakinganysearch,wemustassurethatthisvariableiswithingrangefromourvector.Whatdoesthismeans?Well,supposewehaveavectorwith5elementsandtheuserinputsthenumber8.Whatshouldwedo?
Wealreadyknowthatourvectoris5elementslong,so,ifthenumberthattheuserentersinthesearchisequalorgreaterthanthesizeofourvector,thenitwillbeofrange.
Thisisimplementedusingtheifshownonthefunction.Ifthiscertainconditionoccurs,itwillshowamessageonourprogramstatingthat“ThisIDdoesnotexist”followedbythereturnkeyword.
Thefunctionofreturnistoterminatethefunction.InordertoNOTexecuteanysearch,wemustexitthefunctionbeforeitreachesthenextcode.Becauseofthis,thereturnkeywordisaddedandafterthecoutinsideourcondition,thefunctionimmediatelyendsandreturntothemainfunction.
Ifthevalueenteredbytheuserisavalidone,then,itwilllocatetheinformation.Noticehowinthelasttwocoutsweusethe“[]”operator.Thisiscalledanindexanditisusedtodifferentiatevalueswithinthevector.Itgoesfrom0uptosize()-1.
Let’ssupposethattheuserentersfornamethevalues:John,Michael,Sean.And
![Page 37: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/37.jpg)
forthephones:111111,333333,555555.Then,ourvectorswouldbelikethis:Names=John,Michael,Sean
Phones:111111,333333,555555
Ifwewanttoretrievetheinformation,Names[0]wouldbeJohn;Names[1]wouldbeMichaelandNames[2]wouldbeSean.Thesameoccurswiththephones.Sohere,weusetheIDgiventoretrievethesedataandtheshowittothescreen.
Finally,we’llgotothesearchfunctionbutthistimewewillsearchbythenameofthecontactwewanttofind.Thecodeforthisfunctionlookslikethis:voidSearchByName()
{
boolfound=false;
stringname;
cout<<"\n\nEnterthenametosearch:";cin>>name;
for(inti=0;i!=Names.size();i++){
if(Names[i]==name)
{
![Page 38: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/38.jpg)
{
cout<<"Name:"<<Names[i]<<"\n";cout<<"Phone:"<<Phones[i]<<"\n";found=true;
}
}
if(!found)
{
}
}
Herewedeclaredtwovariables,foundandname.NamewillbethestringthatwewanttolookforandfoundisavariableofdatatypeBOOL(thosethatareonlytrueorfalse)andwilltellusifoursearchwaseithersuccessfulorfailed.
First,werequesttheusertoenterthenametosearchforandafterthis,wewilluseaforlooptocyclethroughalloftheelements.Theaccumulatorisstarted,likeusual,atzero.Now,noticehowourconditionhaschanged:I!=Names.size()
![Page 39: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/39.jpg)
Thankstothislittlefunctionnamedsize(),ourforloopwillbeabletogothroughalltheelementsuntilitreachestheendofitself.Withthissize()function,wecanbecompletelysurethatwedonotgooutofboundofourvector.Ifyoudonotusesize(),thenyouwillhavesomekindofriskloopingthroughthevector.Ifthiserrorhappens,itwillbeonruntimeandthecompilerwontwarnyouaboutthis,soit’ssafertousethesizefunction.
EachlapthatourloophaswillcomparethestringattheIpositioninthevectorwiththestringthattheuserentered.Ifbothstringsareequal,thenitwillshowtheuserthenameandthephoneforthatcontact.Also,itwillchangethestateoffoundtotrue.
Afterexitingtheloop,itwillcheckifthevariablefoundisfalse.Theexclamationsignatthestartofthevariablemeansanegation(NOT)so,iffoundISfalse,thentheflowwillfallontotheblockofcodeoftheifandshowtheuserthemessage“Nocontactwasfoundwiththisname”.
Afterverifyingthestate,thefunctionendsandtheflowoftheprogramreturnstothemainfunction.
cout<<"Nocontactwasfoundwiththisname!\n\n";
![Page 40: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/40.jpg)
CHAPTER5:PROJECT#3SCHOOLNOTESSYSTEM
Thisprojectwillhavecontrolofstudentinformationalongwiththeirnotesstoredintoafileontheharddrive.Also,theprogramwillbeabletocapturethenotesandtogenerateeachstudent’sbulletinandwriteittoanoutputfile(inaplaintextformat).Thefirstthingforstartwillbedefiningtheheaders:#include<fstream>
#include<iostream>
#include<string>
#include<vector>
usingnamespacestd;
Thenewheaderthatyoucannoteis<fstream>.Itstandsfor“filestream”anditcontainsallofthefunctionsandobjectsweneedtomanipulatefilesfromtheoperatingsystem.Thereststaysthesame.Nowlet’sdefinethemainfunction:intmain()
{
intsel=0;
![Page 41: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/41.jpg)
while(true)
{
cout<<"SchoolControl\n\n";cout<<"[1]Addstudent\n";cout<<"[2]Addnotes\n";cout<<"[3]Searchstudent\n";cout<<"[4]Readkardex\n";cout<<"[5]Printkardex\n";cout<<"[6]Exit\n";
cout<<"Choice>";
cin>>sel;
switch(sel)
{
case1:
AddStudent();
break;
case2:
AddNote();
![Page 42: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/42.jpg)
break;
case3:
SearchStudent();
break;
case4:
ReadKardex();
break;
case5:
PrintKardex();
break;
case6:
return0;
![Page 43: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/43.jpg)
break;
default:
break;
}
}
return0;
}
Thisfunctionstaysalmostidenticaltotheoneinourproject1.Wedefinethemenuforthedifferentoptionsandlettheuserdecidewhichpartoftheprogramwantstofollow.Wedefinefunctionsforaddastudent,addnotes,searchforastudent,readkardexandprintkardextoatxtfile.Now,thedefinitionfortheaddStudentpart:voidAddStudent()
{
//Temporalvariable
![Page 44: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/44.jpg)
stringtemp;
//Vectorforholdingallvariablesvector<string>Data;
//[0]FirstName
//[1]LastName
//[2]Phone
//[3]IDnumber
cout<<"Enterstudentfirstname:";cin>>temp;
Data.push_back(temp);
cout<<"Enterlastname:";cin>>temp;
Data.push_back(temp);
cout<<"Enterphonenumber:";cin>>temp;
Data.push_back(temp);
cout<<"Enterstudentnumber:";cin>>temp;
![Page 45: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/45.jpg)
Data.push_back(temp);
//OpenthefileusingtheIDnumberstringfileName;
fileName=Data[3]+".dat";
ofstreamfile;
file.open(fileName.c_str());
//Writethedata
file<<Data[0]<<endl;file<<Data[1]<<endl;file<<Data[2]<<endl;file<<Data[3]<<endl;file.close();
}
Inthisfunction,wedefinetempasthevariableforinputandavectornamedDatawhichwillcontainallofthedataforthenewstudent.Inthecomments,youcanseetheindexwhereeachdataisstored.Afterthis,weuseinputandoutputinstructionstomaketheuserenterthedatafromthestudentandsaveittothevector.
Whenwearefinished,wecreateanewstringnamedmakeFile.Thisstringwillhavethefilenameforthefilewewanttocreate.Inthiscase,itwillbethestudentnumber(storedinData[3])plusthe“.dat”extension.
![Page 46: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/46.jpg)
Theofstreamobject(standingforoutputfilestream)allowsustoopenafileforwritingmode.Weopenthefileusingtheopenfunctionandinsidethecurlybracesthefilename.Thec_str()functionconvertsourstringtoaC-string.
Likethecout<<object,theofstream<<alsosendsoutputinformation,butinthiscasedoesnotgotothedisplay,buttoouroutputfile.Remember!<<operatorsmeanOUTPUTinanystream(iostream,fstream,sstream,estc).
Andfinallyweclosethefile.
voidAddNote()
{
vector<string>Subject;
vector<string>Note;
stringtemp;
stringstudent;
intz=0;
cout<<"EnterthestudentIDtoaddnotes:";cin>>student;
![Page 47: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/47.jpg)
while(true)
{
cout<<"\nEntersubject:";cin>>temp;
Subject.push_back(temp);
cout<<"Enternote:";
cin>>temp;
Note.push_back(temp);
cout<<"Doyouwanttocontinue?[0]Yes[1]No>";cin>>z;
if(z!=0)
{
break;
}
![Page 48: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/48.jpg)
}
stringfileName;
fileName=student+".cal";
ofstreamfile;
file.open(fileName.c_str());
for(inti=0;i!=Subject.size();i++){
}
file.close();
}
TheAddNotefunctionwillcapturethesubjectnamesanditsnotesforanystudent.Wedefinetwovectors,oneforthenamesandtheotheroneforthenotesandaZvariablewhichwillallowtheusertoenterasmanysubjectsashewants.First,thefunctionasksforthestudentIDandafterthat,insideaendlessloop,theuserisrequestedtoenterthesubjectandthenoteforthatsubject.
![Page 49: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/49.jpg)
Afterthis,theprogramaskstheuserforcontinueenteringnotesorexit.
Whenallthesubjectsareentered,wecreateanewfilewiththestudentIDplusthe“.cal”extension.Weopenthefileandwriteinsideofiteachsubjectanditsnote.
Noticehowweloopthroughthevectorandsendtothefilethesubjectandnoteineachpositionandjumpalineattheend.Whenwefinish,thefilemustbeclosed.
voidSearchStudent()
{
stringnumber;
cout<<"InsertstudentID:";cin>>number;
stringfileName;
fileName=number+".dat";
ifstreamfile;
file.open(fileName.c_str());
![Page 50: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/50.jpg)
vector<string>data;
if(file.is_open())
{
file<<Subject[i]<<""<<Note[i]<<endl;stringin;
while(!file.eof())
{
file>>in;
data.push_back(in);
}
cout<<"Firstname:"<<data[0]<<endl;cout<<"Lastname:"<<data[1]<<endl;cout<<"Phone:"<<data[2]<<endl;cout<<"Studentnumber:"<<data[3]<<endl;file.close();
}
![Page 51: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/51.jpg)
else
{
}
}
ThetaskfortheSearchStudentfunctionistolookforadeterminedfilewiththestoreddatafromastudent.Wefirst,requesttheusertoentertheIDandthisIDisconcatenatedtothe".dat”extension.Here,weusetheifstreamobject(inputfilestream).Theifstreamobjectcontainsafunctionnamedis_openthatindicatesusifanyfilehasbeenopenedcorrectly.
Ifthisisthecase,thenwemustreadthefile.Weusethestringintostorethestringsfromthefile.
Thefunctioneof()standsfor“endoffile”andallowustoloopthroughthefileuntilitreachestheend.Westoreallthelinesinsidethedatavectorandafterthereadingisfinished,wesendtothedisplaythedata.
Whenwefinish,thefilemustbeclosed.Ifthefilecouldnotbeopened,theprogramwillshowthemessage“Studentnotfound”tothedisplay.Nowlet’sgototheReadKardex()function:voidReadKardex()
{
![Page 52: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/52.jpg)
stringnumber;
cout<<"InsertstudentID:";cin>>number;
stringfileName;
fileName=number+".cal";
ifstreamfile;
file.open(fileName.c_str());
vector<string>data;
if(file.is_open())
{
cout<<"Studentnotfound\n";stringin;
while(!file.eof())
{
![Page 53: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/53.jpg)
file>>in;
data.push_back(in);
}
file.close();
for(inti=0;i!=(data.size()/2);i+=2){
cout<<data[i]<<"\t"<<data[i+1]<<endl;}
}
else
{
}
}
![Page 54: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/54.jpg)
Asallofthisprogram’sfunctions,requestforthestudentIDandconcatenatesitthe“.dat”extension.Then,triestoopenthisfile.Ifitisopened,thenwecapturewordbywordandaddittothedatavector.Whenitfinished,thefileisclosed.Now,thefollowingforloopmaylookverybizarreforyou.Istartsatzero.TheconditionforthiswillbeIdifferentthanthesizeofthevectordividiedbytwoandthenIwillincrementbytwotimes.Thisloopiswrittenthiswayforallowingustoreadthedatafromthevectorinpairs,asyoucanseeonthecoutline.TherewereadData[i]andData[i+1].
voidPrintKardex()
{
stringnumber;
cout<<"InsertstudentID:";cin>>number;
vector<string>data;
vector<string>notes;
stringfileName1,fileName2;
fileName1=number+".dat";
fileName2=number+".cal";
![Page 55: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/55.jpg)
ifstreamdataFile,noteFile;
dataFile.open(fileName1.c_str());noteFile.open(fileName2.c_str());stringtemp;
if(dataFile.is_open())
{
cout<<"Studentorkardexnotfound\n";while(!dataFile.eof())
{
dataFile>>temp;
data.push_back(temp);
}
}
else
{
![Page 56: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/56.jpg)
cout<<"Studentnotfound\n";return;
}
if(noteFile.is_open())
{
while(!noteFile.eof())
{
noteFile>>temp;
notes.push_back(temp);
cout<<"\n\nREAD:"<<temp<<endl;}
}
else
{
![Page 57: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/57.jpg)
{
cout<<"Kardexnotfound\n";dataFile.close();
}
dataFile.close();
noteFile.close();
//Beginswritingthekardex
ofstreamkardex;
stringfileName3;
fileName3="Kardex"+number+".txt";kardex.open(fileName3.c_str());//Writetitles
kardex<<"STUDENTKARDEX\n\n";kardex<<"NAME:"<<data[1]<<","<<data[0]<<endl;kardex<<"PHONE:"<<data[2]<<endl;kardex<<"NOSTUDENT:"<<data[3]<<endl<<endl;kardex<<"NOTES"<<endl;kardex<<"-------------------------------"<<endl;for(inti=0;i<=(notes.size()/2);i+=2){
}
![Page 58: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/58.jpg)
kardex.close();
cout<<"Kardexgenerated\n\n";}
Finally,thePrintKardex()functionisbasicallyacombinationfromtheSearchStudent()andtheReadKardex().Furthermore,itgeneratesafilenamed“Kardex”+numberID+“.txt”.Insidethisfile,therewillbeareportfromthestudent’sdataanditsnotes.
kardex<<notes[0]<<"\t"<<notes[1]<<endl;
![Page 59: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/59.jpg)
CHAPTER6:PROJECT#4SALESPOINT
Thisprojectwillhaveacatalogofdifferentproduct thataresoldinacommonsupermarket.Alltheproductsarestoredinafileincludingtheirprice.Thisfilecanbemodified.Theprogramgivestheoptiontotheuserforsellingproductstothecustomers, calculating the subtotal, the taxand the final totalof thewholesale.When the sale is finished, the itemquantity and the total are storedon aseparate file. This file stores all the sales and will be used to generate totalreports from the sales. Let’s start as always, with the libraries: #include<cstdlib>
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
usingnamespacestd;
vector<string>products;
vector<float>prices;
These are all known libraries except for<cstdlib>.This is aC library andwe
![Page 60: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/60.jpg)
willuse thefunctionatof,whichwillconvertastringtoafloatvalue.Wewillseethisalittlebitlater.Thetwoglobalvectorswillholdthenameandthevalues(prices)foreachitem.Let’sgotothemainfunction,whichisverysimilartothepreviousprojects:intmain()
{
LoadValues();
intsel=0;
while(true)
{
cout<<"SUPERMARKETSYSTEM\n\n";cout<<"[1]Newclient\n";cout<<"[2]ViewCatalog\n";cout<<"[3]Viewsales\n";cout<<"[4]Exit\n";
cout<<"Select>";
cin>>sel;
switch(sel)
{
![Page 61: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/61.jpg)
case1:
NewClient();
break;
case2:
DisplayCatalog();
break;
case3:
DisplaySales();
break;
case4:
return0;
break;
![Page 62: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/62.jpg)
}
}
return0;
}
Beforeanything,youcanseethatthefirstthingwedoiscalltotheCallValuesfunction.Thisfunctionwillloadthevaluesoftheproductsfromthefilenamed“products.dat”.Lookatthefunction:voidLoadValues()
{
//Theprogramwillloadafilenamed"products.dat"
//Thisinformationwillbestoredtothevectorsstringtemp;
floattval=0.0;
ifstreamproductInfo;
productInfo.open("products.dat");if(productInfo.is_open())
![Page 63: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/63.jpg)
{
while(productInfo>>temp){
products.push_back(temp);
productInfo>>temp;
tval=atof(temp.c_str());
prices.push_back(tval);
}
}
else
{
loaded.\n";
}
![Page 64: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/64.jpg)
}
Theprogramopensthefile“products.dat”andifit’sopen,thenwillreadallthevalues.Thefirstoneisinsertedinproductsandthen,readsagain, thistimeforthe price. The price is read as a cout << "Product information file not found.Data was not return; string, but we cannot make arithmetic operations withstrings, soweuseatof() toconvert fromstring to float.Thisvalue isstored intvalandweinserttvalinthepricesvector.
Returning tomain,wehaveour typicalmenuand theuser isallowed toselectwhich option wants to execute. The first option, NewClient(), will perform anewsale:voidNewClient()
{
intid=0;
intqty=0;
intitemqty=0;
floatsum=0.0;
cout<<"NEWSALE\n";
![Page 65: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/65.jpg)
cout<<"INSTRUCTIONS:\n";cout<<"EntertheIDoftheproduct.Afterthis,enterthequantityandpressenter\n";
cout<<"Ifyouhavefinished,enter-1onproductandwillexit\n\n";
while(true)
{
cout<<"EnterproductID:";cin>>id;
if(id==-1)
{
break;
}
cout<<"Enterquantity:";cin>>qty;
floatvalue=prices[id]*qty;sum=sum+value;
itemqty++;
![Page 66: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/66.jpg)
cout<<endl;
}
floattax=(sum*0.0825);
float total = (sum+(sum*0.0825)); // After the customer has entered all itemscout<<"\nYouhavebought"<<itemqty<<"items\n";cout<<"Subtotal:"<<sum<<endl;cout<<"Tax:"<<tax<<endl;cout<<"Total:"<<total<<endl;floatmoney=0.0;
while(true)
{
menu\n\n";
cout<<"Money:";
cin>>money;
if(money>=sum)
{
![Page 67: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/67.jpg)
cout << "Your change is " << (money-sum) << endl; cout << "Thanks forshopping.Returningtomainbreak;
}
cout<<"Notenoughmoney.Re-entermoney\n";}
//Writethesaletothesalesfileofstreamsales;
//Inofstream,ios::appisaflagthatindicatesthatthedatawritten
//totheoutputwillbeappendedattheendofthefile.
sales.open("sales.dat",ios::app);if(sales.is_open())
{
sales<<itemqty<<"\t"<<total<<endl;sales.close();
}
else
![Page 68: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/68.jpg)
{
}
}
Thefirstthingistodelareourcountervariables.Idwillhavetheidforenteringitems.Theqtywillstorethenumberofthesameitemsboughtbythecustomer.Itemqtywillholdthetotalitemsboughtbythecustomerandsumwillhavethesumofallthepricesoftheproducts.Insideourendlessloop,werequesttheuserto enter the ID for the product. If we do not want to enter a new item andproceedtocheckout,wemustenter-1.Anythingelsewilllookforaitem.Whenaitemisinserted,theusermustenterthequantityofthesameitem.Wecalculatetheitemtotalwiththeproductofthevalueoftheitemandthequantity.
Thisloopwillcontinueforalltheitemsthecustomerwants.Whenheexitswiththe -1, then theprogramgoes to thecheckout.Calculates the taxand the totalanddisplaysthesevaluestothescreen.Theprogramthen,requeststhecustomertoenteraquantityofmoneytopay.Ifheentersavaluethatislowertothetotal,thenitwillnotproceed.Whentheuserentersavalidvalue,thencalculatesthechangeandopens the“sales.dat”file.Note the ios::app.This indicates that thefilewillnotbeoverwritten.Thisvaluewillbeaddedattheendofthefile.Wewillsavetheitemquantityandthetotalofthesaleandfinally,closethefile.
Now,wewilllookattheDisplayCatalog()function.Thisfunctionwillshowthecustomer all the products with their respective price: cout << "SALES FILENOTFOUND!NODATASAVED\n";voidDisplayCatalog()
{
![Page 69: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/69.jpg)
cout<<"Productcatalog\n\n";cout<<"ID\tPRODUCT\tPRICE\n";cout<<"-----------------------------------\n";for(inti=0;i!=products.size();i++){
prices[i]<<endl;
}
cout<<"\n\n";
}
Thisoneisverysimple.Itloopsbothvectorsandshowsonthescreenthevaluesof both vectors at the same position. The last function isDisplaySales(). Thisfunctionwillreadoursalesfileanddisplayareportfromthetotalofsales:voidDisplaySales()
{
cout<<"SUPERMARTKETSALES\n\n";cout<<"Stats\n";
stringtemp;
intsalesCount=0;
![Page 70: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/70.jpg)
intitemCount=0;
floatsumCount=0;
floattval=0.0;
ifstreamsalesFile;
salesFile.open("sales.dat");
if(salesFile.is_open())
{
cout<<"["<<i<<"]\t"<<products[i]<<"\t\t"<<while(salesFile>>temp)
{
salesCount++;
tval=atof(temp.c_str());
itemCount+=tval;
![Page 71: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/71.jpg)
salesFile>>temp;
tval=atof(temp.c_str());
sumCount+=tval;
}
salesFile.close();
}
else
{
cout<<"SALESFILENOTFOUND!Datacannotbegenerated\n\n";return;
}
cout<<"Totalofsales:"<<salesCount<<endl;cout<<"Totalofitemssold:"<<itemCount<<endl;cout<<"Totalearnings:"<<sumCount<<endl;cout<<"\n\n";
![Page 72: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/72.jpg)
}
Wewillinitializeourcountersatzero.Salescountwillholdthenumberofsales.Itemcountthetotalofitems.Sumcountthetotalofmoneysalesandtvalwillbeourtemporalvalueforreading.
Weopenthefile“sales.dat” andwewillreadeverything.First,readtheitemsandconvertittofloatandincrementsalescoundbyoneandalsoitemCountbytval.Afterthis,wereadthenextword,whichisthemoneyofthesale.ThevalueisconvertedtofloatandaddedtosumCount.
Whentheloopends,thefileisclosed.
Finally,weshowtotheoutputthetotalofthisreport.
![Page 73: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/73.jpg)
CHAPTER7:PROJECT#5SIMPLECOMMANDLINEENCRYPTIONSYSTEM
Thisprojectisasimpleencryptionanddecryptionsystem.Encryptionistheprocessofhidinginformationfromplaintextfromtheuser.Thinkalittlebitaboutthefilesthatwehaveusedintheotherprojects.Allofthemareplaintext.Youcanopenthesefilesusingnotepadandyoucanseeallthecontentwithoutanyproblem.Forthestudyingpurpose,thereisnoproblem.However,inrealsystems,theinformationmustbeprotectedandhiddenfromtheuser.Thatistheobjectiveofthisproject.Storinginformationinadifferentwayandafterthis,readingandrestoretherealinfo.Let’slookattheinitialdirectives://Programthatwillencryptanygivenfile//ThisprogramusestheMaptemplateandusescommandlineinput#include<iostream>#include<fstream>#include<cstring>#include<string>#include<map>#include<vector>usingnamespacestd;Therearetwonewlibraries:<cstring>and<map>.ThecstringlibraryisanoriginalClibrarythatwewilluseforstringcomparison.Ithasmanymorefunctionalitiesforstrings,butforthiscase,wewillbelimitedtoonlythatfunction.
![Page 74: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/74.jpg)
Thenextone,map,isaSTLcontainer.Forexplainingthis,lookatthevector.Itholdsmultiplevaluesusingasinglevariablename.Allofthesevaluesaredifferentfromthembytheindex,thatnumberthatweputinsidebrackets.So,what’supwithmap?Well,mapisacontainerwheretheindexisnotanumber.Inmap,whatwestoreissomethingnamedpair.Itconsistoftwointernalvalues:keyandvalue(incode:firstandsecond).Thinkaboutthislikeadictionary.Inthedictionaryyoudonotlookforawordusinganumber.Youlookforadefinitionbyaword,andthatiswhatwedowithmap.map<string,string>theKey;map<string,string>revKey;vector<string>keys;vector<string>values;Thefirstthingwedeclareisourmap.Nowinsidethesymbolsisstring,string.Thismeansthatbothkeyandvaluewillbestrings.Ourothertwovectorswillholdindependentlythekeysandvalues.Revkeywillbethekeyforthedecryptionprocess.Now,herecomesthemostinterestingpart:loadingourvaluesandpopulatingthemap!voidLoadMap()
{
//Mappingtherealvaluevstheencryptedvaluekeys.push_back("a");values.push_back("0");keys.push_back("b");values.push_back("d");keys.push_back("c");values.push_back("b");keys.push_back("d");
![Page 75: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/75.jpg)
values.push_back("x");keys.push_back("e");values.push_back("g");keys.push_back("f");values.push_back("i");keys.push_back("g");values.push_back("z");keys.push_back("h");values.push_back("u");keys.push_back("i");values.push_back("a");keys.push_back("j");values.push_back("c");keys.push_back("k");values.push_back("y");keys.push_back("l");values.push_back("3");keys.push_back("m");values.push_back("q");keys.push_back("n");values.push_back("7");keys.push_back("o");values.push_back("f");keys.push_back("p");values.push_back("p");keys.push_back("q");values.push_back("v");keys.push_back("r");values.push_back("8");keys.push_back("s");values.push_back("e");keys.push_back("t");values.push_back("j");keys.push_back("u");values.push_back("5");keys.push_back("v");values.push_back("h");keys.push_back("w");values.push_back("r");keys.push_back("x");values.push_back("2");keys.push_back("y");values.push_back("m");keys.push_back("z");values.push_back("n");keys.push_back("");values.push_back("");for(inti=0;i!=keys.size();i++){pair<string,string>a;a.first=keys[i];a.second=values[i];theKey.insert(a);a.first=values[i];a.second=keys[i];revKey.insert(a);
}
}
![Page 76: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/76.jpg)
Thiscodeisalittlebittedious.Hereitisthekeyofourencryption.Thefirstrow,usedforkeys,willbeouroriginalvalues.Thesecondrowwillbeourencryptedvalues.Thatmeans,everyletter‘a’willbechangedfora‘0’.Everyletter‘t’willbechangedfora‘j’andsoonwiththerestoftheletters.InthiscodeIdidnotinsertedcapitalletters.So,ourmessagecanonlycontainsmalllettersandspaces.Everythingelsewillnotbeencrypted.Butasyoucansee,itisveryeasytoentermorevaluesinsidethevector.Then,wehaveourloop.Itwillgofromzerotothesizeofourkeys.Inside,wedeclareanewPAIRofvalues,bothoftypestring.Thepairnameis‘a’.Thevalueforfirst(thekey)willbeourkeystringatpositionIandthevalueforoursecond(theactualvalue)willbeinsidetheIpositionofvalues.Afterwecreateourpair,itwillbeinsertedintothemapusingtheinsert()function.Thesamegoesforthedecryptionkeyinrevkey,butherethevaluesareinverse.Now,themainfunctionwillbedifferentthanbefore.Takeaverycloselooktothefollowingpieceofcode:intmain(intargc,char*argv[])
{
//argc-numberofparametersenteredthroughcommandline//argv-parameterenteredfromcommandline//argv[1]-filetoprocess//argv[2]-//-eEncryption//-dDecryptioncout<<"Loadingdata.\n";LoadMap();vector<string>inputData;
![Page 77: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/77.jpg)
stringmessage;stringmessageEnc;stringoutputPath;if(!strcmp(argv[2],"-e"))
{
}
elseif(!strcmp(argv[2],"-d"))
{
}
outputPath+=argv[1];ifstreaminputFile;ofstreamoutputFile;cout<<"Openingfiles.\n";inputFile.open(argv[1]);outputFile.open(outputPath.c_str());if(inputFile.is_open())
{
![Page 78: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/78.jpg)
{
outputPath="ENCRYPTED";outputPath="DECRYPTED";//Obtaintheinputcout<<"Readingfiles.\n";inputFile>>message;//Foreachletterintheinput,generateits//correspondingencryptedvaluefor(inti=0;i!=message.size();i++){cout<<"Encrypting.\n";stringtempChar;tempChar=message.at(i);//Differentiatebetweenencryptinganddecryptingif(!strcmp(argv[2],"-e"))
{
}
elseif(!strcmp(argv[2],"-d"))
{
}
![Page 79: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/79.jpg)
}
else
{
}
}
//Generatetheoutputcout<<"Writingencryptedfile.\n";outputFile<<messageEnc;inputFile.close();outputFile.close();messageEnc+=theKey[tempChar];messageEnc+=revKey[tempChar];
}
else
{
}
![Page 80: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/80.jpg)
cout<<"Processfinished.Outputfileis"<<outputPath<<".\n";cin.get();return0;
}
Whatintheworldisargcandargv?Well,youmayhaveheardaboutcommandline.Inthecommandlineyoucanexecuteprogramsinaverfastinterfaceandhavetheoptiontoconfiguretheseprograms.Thisparticularprogramisdesignedonlytoworkincommandline.AnargumentisavaluethatispassesthroughthecommandlineanditgoesinsideourC++program.Thevariableargcisthecountofargumentsthatourprogramhasreceived.Bydefault,isalwaysone:theprogramname.Thesecondparameter,argv,hastheactualvaluesthattheuserenterstotheprogram.Thisprogramwillreceivetwoarguments:
Thefiletoencrypt/decrypt
Themodeforprocessingcout<<"File"<<argv[1]<<"notfound.\n";Inthefolderwhereyouhaveyourexe,createanewfilenamed“data.txt”andwritesomething,forexample“hello”andsaveit.Afterthis,gotothesettingsofyourprojectandlookforsomethingcalled“ExecutabletoRun/Debug”.After“./$(ProjectName)”enter:data.txt–eTheserepresentthefileyouwanttoencryptand–emeansthatitwillperformanencryption.Thisoptionallowsthecompilertoautomaticallyinsertparametertoyourprogramwithouthavingtogoallthroughcommandline.Butnowlet’sreturntothecode.WeloadourmapsusingLoadMap()functionandavectornamedinputdata.Thisonewillhaveallthestuffthatisinsidethefile.Messagewillhavethetotalmessage.MessageEncwillhavethetransformedmessage.OutputPathwillhavethenameofthefilewheretheencrypted/decryptedmessagewillbewritten.
![Page 81: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/81.jpg)
Afterthis,wewillsianifstructure.Strcmpisastringcomparison.Ifthesecondargument(argv[2])is“-e”thenitmeansthatisisanencryption.So,thefilenamewillhavethe“ENCRYPTED”label.Ifithasthe“-d”string,thenitwillbeadecryption.Then,weproceedtothefileprocessing.Herewewillbeusingbothinputandoutputfilestreams.Theinputhasouroriginalmessageandtheoutputthetransformedmessage.Weopentheinputandreadallthemessage.Afterthis,wewilltreatourstringlikeifitwasavector.Foreachcharacterinsidethestring,willfinditscounterpartonthemapsforitstranslation.However,the[]operatorarenotallowedinastring.Inordertoperformanindexlecture,wemustusetheat()function.TheactualcharacterwillbestoredintothetempCharvariable.Whenwehavethischaracter,werunagainthecomparison.Ifthesecondargumentis“-e”itmeansthatitisanencryption.So,weencrypt.WewillappendattheendofthemessageEnctheVALUEcorrespondingtoitsKEY.So,theKEYwillbetheletterandthevaluewillbethevalueassociatedwiththatkey.AllfromthetheKeymap.Ifitisadecryptionprocess,then,insteadofcomparingwiththeKey,wewillcompareittotherevKeymap.Whenitfinisheswithallthecharacters,amessageappearsinoutconsoleandwritestoouroutputfiletheprocessedmessage.Finally,bothfilesareclosed.Iftheinputfileisnotfound,thenitwillshowanerrormessage.Theprogramdoesnotshowanymessage.Everythinggoestothefiles.Finallywefinishtheprogramandreturnthemainfunction.
![Page 82: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/82.jpg)
CHAPTER8:PROJECT#6DUELGAME
Thisprojectisasimpledemonstrationofanautomatedvideogame,everythingrunningthroughconsole.Themainideaisaduel.Aconfrontationfromcowboyvscowboy.Therearethreedifferentkindsofcowboys:
Basic
Resistence
FastAttack
WheretheBasichasnormalvalues,theresistancehaslowerattackpointbutmorelifepointsandthefastattackhasmoreattackpointsbutlesslifepoints.Theuserwillenterthekindofcowboythathewants.Afterthis,themachinewillrandomlyselectanyofthethree.Inthisprogram,wewilluseclassesfordefiningourtypesofcowboys.Let’slookattheheaders:#include<iostream>
#include<cstdlib>
#include<ctime>
usingnamespacestd;
Thenewheaderinthisprojectis<ctime>.CtimeisanoriginalCheaderandwillbeusedtogeneraterandomnumbers.Now,let’sseeourclasses:c lasscowboy{
public:
![Page 83: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/83.jpg)
intlife;
intplayer;
intmaxatk;
intminatk;
inttype;
cowboy()
{
}
cowboy(intv,intam,intan,intt){
life=v;
maxatk=am;
minatk=an;
![Page 84: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/84.jpg)
type=t;
}
};
ThecowboyclassisourdefinitionforCowboy.Asyoucannotice,itcontainsitsfundamentalvalues:lifepoints,theplayer,themaximumattackpoints,theminimumattackpointsandthetypeofcowboy.
Itsconstructor,cowboy(int,int,int,int)isafunctionthatwillletusassignthefourvaluesinasingleinstructionwhenthecowboyiscreated.BeforegoingintoourDuelclass,let’slookthemainfunction:intmain()
{
dueltheDuel;
theDuel.mainmenu();
system("pause");
return0;
![Page 85: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/85.jpg)
}
Inourmainfunction,weonlydefineaninstanceofourDuelclassandwestarttheduelwiththemainmenufunctionfromDuel.Here,theflowcontrolisinsidetheduel,andnotmain.
classduel
{
public:
duel()
{
}
voidmainmenu()
{
intchoice;
![Page 86: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/86.jpg)
do
{
cout<<"MainMenu\n\n";cout<<"1-Play\n";
cout<<"2-History\n";cout<<"3-Exit\n\n";cout<<"Select:";
cin>>choice;
if(choice==1)
{
}
elseif(choice==2)
{
}
}
![Page 87: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/87.jpg)
while(choice!=3);
}
UpuntilherewedefinetheMainMenuoftheduelasifwewereonthemainmenuonotherprojects.Thisisanotherwayofworkingaroundwithmenus.
voidselectcowboy()
{
cout<<"\n\nSelectyourcowboy:\n\n";cout<<"1-Basic\n";
cout<<"2-Resistence\n";cout<<"3-FastCowboy\n\n";cout<<"Choose:";
intchoice;
cin>>choice;
cowboyplayer;
cowboymachine;
![Page 88: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/88.jpg)
if(choice==1)
{
player.life=30;
player.maxatk=15;
player.minatk=8;
player.player=1;
player.type=1;
}
elseif(choice==2)
{
player.life=50;
player.maxatk=15;
![Page 89: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/89.jpg)
player.minatk=8;
player.player=1;
player.type=2;
}
elseif(choice==3)
{
player.life=28;
player.maxatk=9;
player.minatk=5;
player.player=1;
player.type=3;
}
![Page 90: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/90.jpg)
intrival=rand()%3+1;
if(rival==1)
{
machine.life=30;
machine.maxatk=15;
machine.minatk=8;
machine.player=1;
machine.type=1;
}
elseif(rival==2)
<<machine.life<<"\n\n";{
machine.life=50;
![Page 91: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/91.jpg)
machine.maxatk=15;
machine.minatk=8;
machine.player=1;
machine.type=2;
}
elseif(rival==3)
{
machine.life=28;
machine.maxatk=9;
machine.minatk=5;
machine.player=1;
machine.type=3;
![Page 92: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/92.jpg)
}
else
{
cout<<"Error.Choice="<<choice<<"\n";}
//Iniciaelduelo
cout<<"\n\nPreparingduel\n\n";cout<<"Playerlife:"<<player.life<<"\nMachinelife:"
cout<<"Duelstartsnow!\n\n";bools=true;
while(true)
{
if(s==true)
{
player.minatk)+player.minatk;points\n";
![Page 93: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/93.jpg)
}
else
{
machine.minatk)+machine.minatk;points\n";
"\n";
"\n";
}
cout<<"Player'sremaininglife:"<<player.life<<cout<<"Machine'sremaininglife:"<<machine.life<<if(player.life<=0)
{
}
elseif(machine.life<=0){
![Page 94: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/94.jpg)
}
if(s==true)
{
}
else
{
}
}
}
voidstory()
{
![Page 95: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/95.jpg)
}
};
Let’sexplainthecodeinsideSelectCowboy().Yes,itisverylong,butlet’slookatitveryclosely.
Thefirstthingisthatwerequesttotheplayertoselectwhatkindofcowboydoeshewant.Basic,resistanceorFast.
Afterthis,wecreatetwocowboys,onefortheplayerandanotheroneforthemachine.Thencomesanifinstruction.Iftheuserselectthebasiccowbow,youcanseetheparameterthatwillhavethecowbow.Thesevaluesaretheonesthatchangeineachtypeofcowboy.
Afterthis,wedefinethetypeofcowboythatourrivalwillhaveusingtherand()function.Thisfunctionisincludedinthectimeheader.Thesameconfigurationparametersareappliedforthecowboythatthemachinewilluseintheduel.
Whenwefinishconfiguringthisparameters,finally,theduelstarts.Thesvariable,whichisaboolvariable,willindicateustheturn.Ifsistrue,thentheturnisfortheplayer.Ifthesisfalse,thenit’sthemachine’sturn.
Enteringtheplayer’sturncode,theattackthattheplayerwillhavewillbearandomnumberbetweenitsmaxattackanditsminattack.Duetotheconfigurationoptions,iftheplayerhasthefastattackoption,thentheattackwillbedoubled.However,ifthemachinehastheresistencetype,theattackwillbe
![Page 96: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/96.jpg)
dividedbythree.
Afterthis,thepromptwillshowwithhowmanypointstheattackwasmadeandtheseattackpointswillbesubstractedfromthemachine’slifepoint.Thissameprocesshappenswhenit’sturnforthemachinetoattack.Inthiscase,theplayer’slifepointsaredecreasedinrelationshipwiththemachine’sattackpoints.
Afterbothplayersattack,weshowonthescreentheremaininglifepointsforeachplayerandthenevalueatewetherbothplayersarestillalive.Ifanyofthetwohaszeroornegativelifepoints,thegameendsandshowsamessagewheretheplayerlostorwon.Ifnoneofthishappens,thenthevalueof‘s’willbeinvertedandtheloopwillstaralloveruntilaplayerlosesalloftheirlifepoints.
Finally,thestoryfunctionisonlyanadd-onforthegame.Youcanreplacethesestringwithanythingthatyouwish.
cout<<"Hereyoucaninsertanyhistory\n";cout<<"Fillthispart\n";
![Page 97: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/97.jpg)
CHAPTER9:PROJECT#7POKERGAME
Inthisfinalproject,wewillsimulateafullOOPPokerGame.Here,wewillusemultipleclasses.So,let’sgetstarted.Firstofeverything,wemustdefineourclassforanycard.Herewewillworkwithmultiplefiles,so,createanewfilenamedcard.handaddthiscode:#ifndefCARDH_#defineCARDH_classCard
{
public:intnumber;intsign;voidAssign(int,int);
};
#endifWhenweusemultiplefiles,the#ifndefisapre-processordefinition.Withthis,weassurethatthisfilewillonlybeincludedonce.Ifitisincludedmultipletimesinthesameprogram,willcausetroubleforduplicatedsymbols.So,ourcardwillhaveitsnumber,itssignandafunctionnamedAssign,and
![Page 98: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/98.jpg)
withthisfunction,wewillassigneachcarditsvalues.Now,createanewfilenamed“card.cpp”:#include"card.h"voidCard::Assign(intnum,intsi){number=num;sign=si;
}
Inthisfile,therewillbetheimplementationsofourfunctions.Here,weassigntheparametersfromthefunctiontothevaluesthattheobjectwillhave.Noticethatwemustincludeour“card.h”file.Thatistheonethatwecreatedbefore.Itmustbeincludedsoitcanimplementthefunctions.Nowthatwehavethecardclasss,wemustcreatetheplayerclass.Player.hdefineslike:#ifndefPLAYERH_#definePLAYERH_#include<iostream>#include<string>#include<vector>#include"card.h"usingnamespacestd;classPlayer
{
![Page 99: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/99.jpg)
public:stringname;vector<Card>hand;voidGetCard(Card);voidShowHand();
};
#endifThePlayerclasswillhavetwoproperties:thenameoftheplayerandavector.Look:herewedonotuseanystring.ItisaCARD!Theclasswedefinedpreviously.Thisvectorofcardscanbeviewedlikethehandthattheplayerowns.Also,wehaveafunctionnamedGetCard(),thisfunctionwillallowourplayertoreceivecardsandaddthemtoitshand.Andfinally,thefunctionShowHand().Thiswillonlyshowthevaluesinsidethehand.Let’sseetheimplementationthatwillbeinside“Player.cpp”:#include<vector>#include"card.h"#include"player.h"usingnamespacestd;voidPlayer::GetCard(Cardc)
{
![Page 100: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/100.jpg)
hand.push_back(c);
}
voidPlayer::ShowHand()
{
cout<<name<<"'shand:";for(inti=0;i!=hand.size();i++){cout<<hand[i].sign<<"-"<<hand[i].number<<"";}cout<<endl;
}
Inthisimplementation,wemustincludeCardandPlayerbecausewewillbeusingboth.ThefunctionCardreceivesaparameteroftypeCardandisinsertedinthehand.Theshowhandloopsthroughthehandoftheplayer,obtainsthevaluesforeachcardanddisplaysthemtothescreen.But…whowillgivethecards?Thedealerobviously!Let’sdefineaclassforourdealerin“dealer.h”:#ifndefDEALERH_#defineDEALERH_#include<string>#include<vector>#include"card.h"
![Page 101: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/101.jpg)
usingnamespacestd;classDealer
{
public:vector<Card>Deck;Dealer();CardGiveCard();voidShuffleCards();
};
#endifThedealeronlyhasonepropertybutitisthemostimportantpropertyfromthegame:Thedeck!Andhowwillwerepresentdedeck?Alsoasanvectorofcards.Thedealerwillalsohavethehabilitytogivecardsandtoshufflethecards.Now,letslooktheimplementation:#include<algorithm>#include<vector>#include<string>#include<random>#include<chrono>
![Page 102: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/102.jpg)
#include"dealer.h"#include"card.h"usingnamespacestd;CardDealer::GiveCard()
{
Cardc=Deck[0];Deck.erase(Deck.begin());returnc;
}
voidDealer::ShuffleCards()
{
unsignedseed=std::chrono::system_clock::now().time_since_epoch().count();shuffle(Deck.begin(),Deck.end(),std::default_random_engine(seed));}Dealer::Dealer()
{
![Page 103: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/103.jpg)
for(inti=0;i!=12;i++){for(intj=0;j!=4;j++)
{
CardnewCard;newCard.number=(i+1);newCard.sign=(j+1);Deck.push_back(newCard);
}
}
}
Hereweinsertednewlibraries:
Algorithm:willbeusedtoshuffleourdeck
Random:generatearandomnumber
Chrono:accesstotiminglibrariesFirst,lookattheGiveCard().Itwillselectthecardthatisonthetopofthedeck.Willremoveitformthemandthenextractittoanotherpart,thatwouldbethehandofanyplayer.OntheShuffleCards().Wewillgenerateatime-basedseedwhichwewilluseforshufflingthedeckinarandomorder.Also,lookatthe
![Page 104: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/104.jpg)
Dealer()function.Ithasanestedloop(aloopinsideanotherloop)and,withthis,wegeneratethecards.From1to12andeachfrom1to4.Afterthis,eachcardisinsertedtothedeckandnowthedeckiscreated!Now,themostimportantpart,themainfunction:#include<iostream>#include<string>#include<vector>#include"player.h"#include"card.h"#include"dealer.h"usingnamespacestd;//NumberofcardsallowedinhandintCardNumber=5;intmain()
{
//CreateplayersPlayerplayer1;Playerplayer2;player1.name="CPU";stringname;cout<<"Enteryourname:";cin>>name;player2.name=name;
![Page 105: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/105.jpg)
DealertheDealer;theDealer.ShuffleCards();//Givecardstotheplayersfor(inti=0;i!=CardNumber;i++){player1.GetCard(theDealer.GiveCard());player2.GetCard(theDealer.GiveCard());}player2.ShowHand();cout<<"\n";player1.ShowHand();return0;
}
Therearenounknownlibraries.Rememberthatwemustaddallofourclassheaders.ThereistheconstantCardNumber.Itwillbeusedbythedealerforgivingcards.Whenthemainfunctionstarts,twoplayersarecreated.Weassignplayer1thename“CPU”andforplayer2,thenamewillbegivenbytheuser.Afterthiswecreatethedealer(andbycreatingthedealer,alsothedeckiscreated)andtellthedealertoshufflecards.Now,from0toCardNumber,thedealerwillobtainacardforeachplayer,removeitfromthedeckandgiveittothehandoftheplayer.Afterthis,bothhandsareshownandtheoutcomeofthegamecanbedetermined.Inthisexample,itcanbeveryeasytounderstandhowallofthesereallifeobjectsareabstractedandtakentoaprogrammingparadigmlikeC++.Herethereisnofunctionallogic,onlyOOPlogic.
![Page 106: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/106.jpg)
CHAPTER10:WHATTODONEXT
Upuntilnow,wecoveredsomebasicandintermediatestuffconcerningC++.However,inordertomasterC++,therearemorespecializedtopicsthatshouldbelearned.
Memorymanagement:Theuseofthememoryavailablefromtheoperatingsystemintoourobjects.Thekeywordsnewanddelete.Withthesetwokeywords,youcanmanagehowmanymemoryisbeingused,assignwhenandtowhomassignmemoryandevenoptimizeyourprograms.
StandardTemplateLibrary:Inthiscoursewecoveredonlytwotemplates:mapandvector.However,theC++’sSTLiswaybeyondthisthesetwoobjects.Structureslikethestack,queue,list,dequeandmorearebuilt-inwithinC++.
Iterators:TheiteratorsisthewaythatC++loopsthroughthetemplatesbutdonotuseindexes.Instead,theiteratorsadapttotheneededcontainer.
Pointers:PointersareaveryimportantpartofC++andwillallowyoutohaveabettermemorymanagementandcreatemultipleobjectssavinghugeamountsofmemory.
Stringmanagement:Multipleoperationscanberealizedusingstrings.Searchforpatterns,complexconcatenation,tokenizetokens,processingstrings,replacingtotallyorpartiallystrings,etc.
FundamentsofOOP:AlthoughwecoveredsomepointsfromOOPinthesampleprojects,thiscoursewasnotaboutOOP.Soitwouldbeagoodideatocoverfull
![Page 107: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/107.jpg)
OOPtheoryinordertogeneratebetterdesignofprogramming.Someconceptswouldbeclass,abstraction,member,memberfunctions,simpleinherence,multipleinherenceandevenpolymorphism.
Createyourownlibraries:Aswesawonthecourse,youcangenerateyourown.hand.cppfiles.Hereweusedthemasexternallinkingforclasses.Butitcanbealsoimplementedwithyourownhome-madefunctions.Youmighthavefunctionsthatyouneedtousemultipletimesanddonotwanttohavetorewritethemseveraltimes.So,agoodideawouldbetoimplementallofthesefunctionsinasingle.cppfileandaddittoafutureproject.
Ifyoucoverallofpointsmentionedhere,youcanmoveontomoreadvancedfeatureslike:
Templates
Operatoroverloading
Complexfileprocessing
Graphicalprogramming
Onwindows:MicrosoftFoundationClasses
OnLinux:GTK+orQT
Even,withgraphicalprogramming,thereistheOpenGLopensourceprogramming.WithOpenGLyoucangenerate2Dand3DgraphicsusingC++.Inthe2Dmode,youcandrawmultiplefiguresusingvertexandmatrix.Youcanaddtextures,colorsandrefreshscreenwheneveryouwant.Inthe3Dmode,youcandesignyourown3Denvironments,definetexturesand3Dmodels.Atthis
![Page 108: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/108.jpg)
point,animationsbecomeaccessible.Also,inbothmodes,youcanenabletheuseofthekeyboardandassignactionswitheachkey.WithOpenGLyoucanalsodesignvideogames,fromtheeasiesttothehardest.Itdependsonyourprogrammingskills.Moreover,OpenGLalsoenablesyoutoaddbackgroundaudios,andallofthisusingC++.However,youshouldtakenotethatOpenGLrunswellontheMicrosoftVisualStudiocompiler.ExtraconfigurationsmightbeneededintheGNUG++compiler.Asyoucansee,thelimitinC++programmingisuptoyourimagination.
![Page 109: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/109.jpg)
CONCLUSION:
Afterthetopicswehavecovered,youcanhaveaclearersceneofhowC++programmingisdeveloped.WehavetriedtohaveanappliedaspectoftheapplicationsofC++.Thereasonisthatmanytimes,theuserdoesnotunderstandhowallthepiecescanworktogetherasacompletesystem.Sowehavebeencarefulintheappliedfocusforthiscourse.Asyoumighthavenoticed,thecomplexprogramsare,attheend,aremadeusingthesamebasicinstructionsexplainedinchapterone.Oneexampleofthisisthecreationofamenu:herewehavevariabledeclaration,aninfiniteloop,aswitchstatementandsomeinput.Usingthesebasicstructureswecanbuildthemenuandmanymorestuff.Onethingthatwehavetoremember(andthatmanypeopledon’tsee)isthattheconsoleisnottheonlyoutput.Youmightthinkthattheconsoleiscompletelyuselessandisnotattractive.And,inacertainway,thisisright.Theconsoleisnottheappropriateinputandoutputsystemformostprogramminginthesedays.However,remember:thepowerofC++isitsspeed,itscomplexityanditsSTL.Theinputandoutputsystemcanbealwayschanged:sometimesitcanbefromconsole,othertimescanbeafile,andanotheragraphicaluserinterface(GUI)orwhateveryouwant.Butdon’tbemistakenbythefalsefactthattheprogramsthatareuglyarecompletelyuseless.Havingthiscourse,youcanadvancetoamorecomplexgraphicalsystem,whereyoucanmakemorecomfortablesoftwarewhilestillhavingthepowerofC++.ExamplesofthisisGTK+orQT.WiththeseC++expansions,youcandesigngraphicalinterfacesforcomplementingyourprojects.ThiscoursealsocoveredsomefeaturesthatC++inheritsfromitspredecessor,C,likethemathfunctions.Thesearenottheonlyones.YoucandiveupintothecompleteClibraryandfindabunchmoreoftoolstouseinyourC++programming,justremembertomakethepropertypeconversions.Afterthiscourse,youarenowabletodevelopyourownsolutions.Andyouarenotlimitedbythesolutions.Now,youcandofileprocessing,datastorage,reportcreation,datatypeconversionandmorefeaturesthatarewidelyusedforcalculations.Somethinghastobesaid:plaintextisnotthebestwaytosaveinformation.Theoptimalwaywouldbeadatabase.Butthisisamorecomplex
![Page 110: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/110.jpg)
tocoverinabasiccourse.However,withthisbasicknowledgeofdatastorage,youcanmoveontoabetterstoringtechnique.Afterthispoint,itisintheinterestofthiscoursethatyouarenowabletointerpretC++codeandtoprovidesolutionsusingthelanguage.Manyresourcesareavailableontheinternet,likereferencepages,thatcancomplementallofyourC++knowledgeandthatyoumightnow,withtheconceptsthatwehavecovered,understandanimplementnewfunctionalities.Nowthequestionwouldbe,whatareyougoingtodowithyournewlyacquiredknowledge?
![Page 111: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/111.jpg)
DIDYOUENJOYTHISBOOK?
Iwanttothankyouforpurchasingandreadingthisbook.Ireallyhopeyougotalotoutofit.
CanIaskaquickfavorthough?
IfyouenjoyedthisbookIwouldreallyappreciateitifyoucouldleavemeapositivereviewonAmazon.
IlovegettingfeedbackfrommycustomersandreviewsonAmazonreallydomakeadifference.Ireadallmyreviewsandwouldreallyappreciateyourthoughts.
Thankssomuch.
W.BEan
p.s.YoucanclickheretogodirectlytothebookonAmazonandleaveyourreview.
![Page 112: C++ In One Day: The Ultimate Beginners Guide To C++ With 7 Awesome Projects](https://reader036.vdocuments.mx/reader036/viewer/2022090906/613ca219f046235e845ce16b/html5/thumbnails/112.jpg)
ALLRIGHTSRESERVED.Nopartofthispublicationmaybereproducedortransmitted in any form whatsoever, electronic, or mechanical, includingphotocopying, recording, or by any informational storage or retrieval systemwithoutexpresswritten,datedandsignedpermissionfromtheauthor.