Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with...
Transcript of Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with...
CharacterFunctions&ManipulatorsArraysinC++
CS16:SolvingProblemswithComputersILecture#10
ZiadMatni
Dept.ofComputerScience,UCSB
LectureOutline
• Usefulcharactermanipulators&functions
• ArraysinC++
5/8/18 Matni,CS16,Sp18 2
MemberFunctions:getandgetline
• Allowyoutouseinputstreamsthatincludewhite-spaces– Unlikecin,whichseparatesinputsbywhite-spaces– Recall:white-space=space,tab,newlinecharacters
5/8/18 Matni,CS16,Sp18 3
charc_fin,c_cin;ifstreaminf;inf.get(c_fin);cin.get(c_cin);
stringfstring,cin_string;ifstreaminf;getline(inf,fstring);getline(cin,cin_string);
.get .getline
Seedemofiles:get_example.cppgetline_example.cpp
getlinefunction• Forstandardinputs,cinisfine:butitignoresspace,tabs,andnewlines
• Sometimes,youwanttogettheentirelineofdata!– Andstopatthenewline
• Besttousethefunctiongetlineforthatpurpose.
• Youhavetoincludethe<iostream>library(whichyoulikelyalreadydo!)• PopularUsage:
getline(ifstream_object,string); getline(cin,string);
5/8/18 Matni,CS16,Sp18 4
AdditionalNoteAboutgetline
• Youcancustomizewhatcharacteragetlinestops“getting”info– Youcandefinethe“characterdelimiter”– Bydefault,that’sanewlinechar
Example:getline(cin,VariableX,‘m’) //stopsatthechar‘m’
Ifthestandardinputis “Hello,Imustbegoing”, thenVariableXwillbe “Hello,I”
5/8/18 Matni,CS16,Fa17 5
CharacterFunctions
• Severalpredefinedfunctionsexisttofacilitateworkingwithcharacters
• Thecctypelibraryisrequiredformostofthem #include<cctype> usingnamespacestd;
5/8/18 Matni,CS16,Sp18 6
ThetoupperFunction
• toupperreturnstheargument'suppercasecharacter– toupper('a')returns'A'– toupper('A')returns'A'
DOESNOTWORKWITHSTRINGS!IT’SFORCHARACTERSONLY!
5/8/18 Matni,CS16,Sp18 7
ThetolowerFunction
• Similartotoupperfunction…
• tolowerreturnstheargument'slowercasecharacter– tolower('a')returns'a'– tolower('A')returns'a'
5/8/18 Matni,CS16,Sp18 8
TheisspaceFunction
• isspacereturnstrueiftheargumentisawhitespace(spaces,tabs,andnewlines)
– So,isspace('')returnstrue,sodoesisspace(‘\n’)Example:
if(isspace(next))cout<<'-';
elsecout<<next;
Printsa'-'ifnextcontainsaspace,tab,ornewlinecharacter
5/8/18 Matni,CS16,Sp18 9
5/8/18 10
CharacterManipulatorsWorkToo!
• Include<cctype>tousewith,forexample,toupper()strings=“hello”;s[0]=toupper(s[0]);cout<<s;//Willdisplay“Hello”
• …ortousewithtolower()strings=“HELLO”;for(inti=0;i<5;i++)s[i]=tolower(s[i]);cout<<s; //Willdisplay“hello”
5/8/18 Matni,CS16,Sp18 11
Manipulators
• Atypeoffunctioncalledinanontraditionalway
• Manipulators,inturn,callmemberfunctions– Mayormaynothaveargumentstothem
• Usedaftertheinsertionoperator(<<)asifthemanipulatorfunctioncallisanoutputitem
5/8/18 Matni,CS16,Sp18 12
ThesetwManipulator
• setwsetsspacesforoutput:onlyeffectiveforoneuse– Foundinthelibrary<iomanip>
• Example:cout<<"Start"<<setw(4)<<10 <<setw(4)<<20<<setw(6)<<30; produces:Start102030
2 Spaces 4 Spaces
• The 1st setw(4) ensures 4 spaces between “Start" and 10, INCLUSIVE of the spaces taken up by 10. • The 2nd setw(4) ensures 4 spaces between 10 and 20, INCLUSIVE of the spaces taken up by 20. • The 3rd setw(6) ensures 6 spaces between 20 and 30, INCLUSIVE of the space taken up by 30.
135/8/18 Matni,CS16,Sp18
ConvertingDataTypesinC++stoi to_string
stoi() String-to-Integerconversion• Foundin<string>library.• Takesstringasargumentandreturnsinttype.• Example: intx=stoi(“66”)//x=66• IfthestringisNOTanumberrepresentation,itwillcausearuntimeerror!
to_string() Number-to-Stringconversion• Foundin<string>library.• Takesintordoubleasargumentandreturnsstringtype.• Example: stringy=to_string(6.32)//y=“6.32”
5/8/18 Matni,CS16,Sp18 14
ConvertingDataTypesinC++CombiningCharacterswithStrings
• ConsiderthiscodeusingC++Strings:stringmsg1="Hello",msg2="World";charsp='';//spacecharacterstringmsg3=msg1+msg2;stringmsg4=msg1+sp+msg2;stringmsg4=msg1+sp+msg2[0];stringmsg4=msg1[0]+sp+msg2[0];
• Youcancreateastringthatisaconcatenationofstrings+characters• YouCANNOTcreateastringoutofonlycharacters!– Concatenationisjustforstrings-notforcharacters.
5/8/18 Matni,CS16,Sp18 15
Compiles!
AlsoCompiles!
AlsoCompiles!
DoesNOTCompile!
ARRAYS
5/8/18 Matni,CS16,Sp18 16
IntroductiontoArrays
• Anarrayisusedtoprocessacollectionofdataofthesametype– Examples: Alistofpeople’slastnames Alistofnumericalmeasurements
• Whydoweneedarrays?– Imaginekeepingtrackof1000testscoresinmemory!• Howwouldyounameallthevariables?• Howwouldyouprocesseachofthevariables?
5/8/18 Matni,CS16,Sp18 17
DeclaringanArray
intscore[5]; //Declaresanarrayofintscalledscorethathas5elements://score[0],score[1],score[2],score[3],score[4] subscriptorindex
• Notethesizeofthearrayisthehighestindexvalue+1– BecauseindexinginC++startsat0,not1– Theindexcanbeanintegerdatatypevariablealso
5/8/18 Matni,CS16,Sp18 18
LoopsAndArrays
• for-loopsarecommonlyusedtostepthrougharrays
Example:intmax=9,size=5; for(i=0;i<size;i++) cout<<max–score[i]<<endl;displaysthedifferencebetweeneachscoreandthemaximumscorestoredinanarray
5/8/18 Matni,CS16,Sp18 19
First index is 0
Last index is (size – 1)
DeclaringAnArray
• Whenyoudeclareanarray,youMUSTdeclareitssizeaswell!
intMyArray[5]; //Arraydeclaredhas5non-initializedelementsintMyArray[]={1,2,5,7,0};//Arraydeclaredhas5initializedelementsintMyArray[5]={1,2,5,7,0};//Thisisoktoo!
5/8/18 Matni,CS16,Sp18 20
{ … } used for full-array initializations
InitializingArrays
• It’srecommendedtoinitializeanarraywhenitisdeclared– Thevaluesfortheindexedvariablesareenclosedinbracesandseparatedbycommas
• Example:intchildren[3]={2,12,1};Isequivalentto: intchildren[3]; children[0]=2; children[1]=12; children[2]=1;
5/8/18 Matni,CS16,Sp18 21
ConstantsandArrays
• Youcanusevariablesasindicesinarrays,BUTNOTtodeclarethem!• However,youcanuseconstantstodeclaresizeofanarray
Example:constintNUMBER_OF_STUDENTS=50;//canchangethislaterintscore[NUMBER_OF_STUDENTS]; …for(inti=0;i<NUMBER_OF_STUDENTS;i++) cout<<score[i]<<endl;
• Tomakethiscodeworkforanynumberofstudents, simplychangethevalueoftheconstantinthe1stline…
5/8/18 Matni,CS16,Sp18 22
5/8/18 Matni,CS16,Sp18 23
WhenreservingmemoryspaceforanarrayinC++,thecompilerneedstoknowjust3things:1. Astartingaddress(location)2. Howmanyelementsinarray3. Whatdatatypethearrayelementsare
Ifthecompilerneedstodeterminetheaddressofa[3],forexample
Itstartsata[0](itknowsthisaddress!)Itcountspastenoughmemoryforthreeintegerstofinda[3]
ArrayIndexOutofRange
• Acommonerrorbyprogrammersisusinganonexistentindex• Indexvaluesforinta[6]arethevalues0through5• Anindexvaluethat’snotallowedbythearraydeclaration iscalledoutofrange
• Usinganoutofrangeindexvaluedoesnotalwaysproduceanerrormessagebythecompiler!!!– ItproducesaWARNING,buttheprogramwilloftengivearun-timeerror– So,DON’Trelyonthecompilercatchingyourmistakes!BeProactive!
5/8/18 Matni,CS16,Sp18 24
OutofRangeProblems
• Let’ssaywehavethefollowing:inta[6],i=7;• Thenweexecutethestatement: a[i]=238;• Thiscauses…– Thecomputertocalculatetheaddressoftheillegala[7]– Thisaddresscouldbewheresomeothervariableintheprogramisstored!– Thevalue238willbestoredattheaddresscalculatedfora[7]
• Congrats!You’venowmessedwiththeintegrityofcomputermemory!• Youcouldgetrun-timeerrorsORYOUMIGHTNOT!!!(unpredictable)• Thisisbadpractice!Keeptrackofyourarrays!
5/8/18 Matni,CS16,Sp18 25
Seedemofiles:basic_arrays.cpp
DefaultValues
• Iftoofewvaluesarelistedinaninitializationstatement– Thelistedvaluesareusedtoinitializethefirstoftheindexedvariables– Theremainingindexedvariablesareinitializedtoazeroofthebasetype
• Example:inta[10]={5,5};//Notearraysizegiven initializesa[0]anda[1]to5 anda[2]througha[9]to0
NOTE:ThisiscalledanextendedinitializerlistanditonlyworksinthelatestversionsofC++compilers(version11orlater).5/8/18 Matni,CS16,Sp18 26
Range-BasedForLoops• C++11(andlater)includesanewtypeofforloop:Therange-basedfor-loopsimplifiesiterationovereveryelementinanarray.
• Forexample,thefollowingcodeoutputs:2468
intarr[]={2,4,6,8};for(intx:arr){ cout<<x<<“”;}
5/8/18 Matni,CS16,Sp18 27
ArraysinFunctions• Indexedvariablescanbeargumentstofunctions• Example:Ifaprogramcontainsthesedeclarations:
voidmy_function(intx); ... inti,n,a[10];
Variablesa[0]througha[9]areoftypeint,somakingthesecallsISlegal: my_function(a[0]); my_function(a[3]); my_function(a[i]);
BUT!ThiscallisNOTlegal: my_function(a[]); or my_function(a);
5/8/18 Matni,CS16,Sp18 28
ArraysasFunctionArguments
• Youcanmakeanentirearrayaformalparameterforafunction– Thatis,asaninputtoafunction
• ButyoucannotmakeanentirearraytheRETURNEDvalueforafunction– Thatis,asanoutputfromafunction
• Anarrayparameterbehavesmuchlikeacall-by-referenceparameter
5/8/18 Matni,CS16,Sp18 29
PassinganArrayintoaFunction
• Anarrayparameterisindicatedusingemptybracketsintheparameterlistsuchasvoidfill_up(inta[],intsize);
5/8/18 Matni,CS16,Sp18 30
FunctionCallsWithArrays• Iffunctionfill_upisdeclaredinthisway (note:uses[]!!!)
voidfill_up(inta[],intsize);
• andarrayscoreisdeclaredthisway:intscore[5],number_of_scores=5;
• fill_upiscalledinthisway (note:no[]!!!) fill_up(score,number_of_scores);
• Notethatthearrayvaluescanbechangedbythefunction– Eventhoughit“lookslike”it’sbeingpassed-by-value–it’sactuallybeingpassed-by-reference.We’lldiscussthismorewith“pointers”anothertime…
5/8/18 Matni,CS16,Sp18 31
5/8/18 Matni,CS16,Sp18 32
ArrayArgumentDetails
• Recall:Whatdoesthecomputerknowaboutanarray?– Thebasetype– Theaddressofthefirstindexedvariable– Thenumberofindexedvariables
• Whatdoesafunctionneedknowaboutanarrayargument?– Thebasetype– Theaddressofthefirstindexedvariable
5/8/18 Matni,CS16,Sp18 33
ArrayParameterConsiderations
• Becauseafunctiondoesnotknowthesizeofanarrayargument…– Theprogrammershouldincludeaformalparameterthatspecifiesthesizeofthearray
– Thefunctioncanprocessarraysofvarioussizes• Example:functionfill_upfromonpg.392ofthetextbookcanbeusedtofillanarrayofanysize:fill_up(score,5);fill_up(time,10);
5/8/18 Matni,CS16,Sp18 34
But…ISthereawaytoCALCULATEtheSizeofanArray?• Yes,thereis…butnotwithregulararrays• Youwillwanttouse“dynamicarrays”– We’lltalkaboutthoselateronwith“pointers”
• Fornow,getusedtotheideaofpassingthesizeofanarrayintoafunctionthathasthearrayasargument.
5/8/18 Matni,CS16,Sp18 35
constModifier• Arrayparametersallow
afunctiontochangethevaluesstoredinthearrayarg.– Similartohowaparameterbeingpassedbyreferencewouldbe
• Ifyouwantafunctiontonotchangethevaluesofthearrayargument,usethemodifierconst
• Anarrayparam.modifiedw/constiscalledaconstantarrayparameter– Example:voidshow_the_world(constinta[],intsize);
• Ifconstisusedtomodifyanarrayparameter:ithastobeusedinboththefunctiondeclarationanddefinition
5/8/18 Matni,CS16,Sp18 36
Seedemofiles:array_function.cpp
ReturningAnArray
• Recallthatfunctionscanreturnavalueoftypeint,double,char,…,orevenaclasstype(likestring)
• BUTfunctionscannotreturnarrays
• We’lllearnlaterhowtoreturnapointertoanarrayinstead…
5/8/18 Matni,CS16,Sp18 37
YOURTO-DOs
q BeginLab6onWednesdayq DoHW10bynextThursday
q VisitProf’sandTAs‘officehoursifyouneedhelp!
q Practiceallyourskills
5/8/18 Matni,CS16,Sp18 38
5/8/18 Matni,CS16,Sp18 39