Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with...

39
Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB

Transcript of Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with...

Page 1: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

CharacterFunctions&ManipulatorsArraysinC++

CS16:SolvingProblemswithComputersILecture#10

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

LectureOutline

•  Usefulcharactermanipulators&functions

•  ArraysinC++

5/8/18 Matni,CS16,Sp18 2

Page 3: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 4: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 5: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 6: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

CharacterFunctions

•  Severalpredefinedfunctionsexisttofacilitateworkingwithcharacters

•  Thecctypelibraryisrequiredformostofthem #include<cctype> usingnamespacestd;

5/8/18 Matni,CS16,Sp18 6

Page 7: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ThetoupperFunction

•  toupperreturnstheargument'suppercasecharacter– toupper('a')returns'A'– toupper('A')returns'A'

DOESNOTWORKWITHSTRINGS!IT’SFORCHARACTERSONLY!

5/8/18 Matni,CS16,Sp18 7

Page 8: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ThetolowerFunction

•  Similartotoupperfunction…

•  tolowerreturnstheargument'slowercasecharacter– tolower('a')returns'a'– tolower('A')returns'a'

5/8/18 Matni,CS16,Sp18 8

Page 9: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 10: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

5/8/18 10

Page 11: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 12: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

Manipulators

•  Atypeoffunctioncalledinanontraditionalway

•  Manipulators,inturn,callmemberfunctions– Mayormaynothaveargumentstothem

•  Usedaftertheinsertionoperator(<<)asifthemanipulatorfunctioncallisanoutputitem

5/8/18 Matni,CS16,Sp18 12

Page 13: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 14: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 15: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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!

Page 16: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ARRAYS

5/8/18 Matni,CS16,Sp18 16

Page 17: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

IntroductiontoArrays

•  Anarrayisusedtoprocessacollectionofdataofthesametype– Examples: Alistofpeople’slastnames Alistofnumericalmeasurements

•  Whydoweneedarrays?– Imaginekeepingtrackof1000testscoresinmemory!•  Howwouldyounameallthevariables?•  Howwouldyouprocesseachofthevariables?

5/8/18 Matni,CS16,Sp18 17

Page 18: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 19: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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)

Page 20: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 21: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 22: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 23: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

5/8/18 Matni,CS16,Sp18 23

WhenreservingmemoryspaceforanarrayinC++,thecompilerneedstoknowjust3things:1.  Astartingaddress(location)2.  Howmanyelementsinarray3.  Whatdatatypethearrayelementsare

Ifthecompilerneedstodeterminetheaddressofa[3],forexample

Itstartsata[0](itknowsthisaddress!)Itcountspastenoughmemoryforthreeintegerstofinda[3]

Page 24: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ArrayIndexOutofRange

•  Acommonerrorbyprogrammersisusinganonexistentindex•  Indexvaluesforinta[6]arethevalues0through5•  Anindexvaluethat’snotallowedbythearraydeclaration iscalledoutofrange

•  Usinganoutofrangeindexvaluedoesnotalwaysproduceanerrormessagebythecompiler!!!–  ItproducesaWARNING,buttheprogramwilloftengivearun-timeerror–  So,DON’Trelyonthecompilercatchingyourmistakes!BeProactive!

5/8/18 Matni,CS16,Sp18 24

Page 25: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 26: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 27: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 28: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 29: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ArraysasFunctionArguments

•  Youcanmakeanentirearrayaformalparameterforafunction–  Thatis,asaninputtoafunction

•  ButyoucannotmakeanentirearraytheRETURNEDvalueforafunction–  Thatis,asanoutputfromafunction

•  Anarrayparameterbehavesmuchlikeacall-by-referenceparameter

5/8/18 Matni,CS16,Sp18 29

Page 30: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

PassinganArrayintoaFunction

•  Anarrayparameterisindicatedusingemptybracketsintheparameterlistsuchasvoidfill_up(inta[],intsize);

5/8/18 Matni,CS16,Sp18 30

Page 31: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 32: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

5/8/18 Matni,CS16,Sp18 32

Page 33: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ArrayArgumentDetails

•  Recall:Whatdoesthecomputerknowaboutanarray?– Thebasetype– Theaddressofthefirstindexedvariable– Thenumberofindexedvariables

•  Whatdoesafunctionneedknowaboutanarrayargument?– Thebasetype– Theaddressofthefirstindexedvariable

5/8/18 Matni,CS16,Sp18 33

Page 34: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ArrayParameterConsiderations

•  Becauseafunctiondoesnotknowthesizeofanarrayargument…– Theprogrammershouldincludeaformalparameterthatspecifiesthesizeofthearray

– Thefunctioncanprocessarraysofvarioussizes•  Example:functionfill_upfromonpg.392ofthetextbookcanbeusedtofillanarrayofanysize:fill_up(score,5);fill_up(time,10);

5/8/18 Matni,CS16,Sp18 34

Page 35: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

But…ISthereawaytoCALCULATEtheSizeofanArray?•  Yes,thereis…butnotwithregulararrays•  Youwillwanttouse“dynamicarrays”– We’lltalkaboutthoselateronwith“pointers”

•  Fornow,getusedtotheideaofpassingthesizeofanarrayintoafunctionthathasthearrayasargument.

5/8/18 Matni,CS16,Sp18 35

Page 36: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

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

Page 37: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

ReturningAnArray

•  Recallthatfunctionscanreturnavalueoftypeint,double,char,…,orevenaclasstype(likestring)

•  BUTfunctionscannotreturnarrays

•  We’lllearnlaterhowtoreturnapointertoanarrayinstead…

5/8/18 Matni,CS16,Sp18 37

Page 38: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

YOURTO-DOs

q BeginLab6onWednesdayq DoHW10bynextThursday

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Practiceallyourskills

5/8/18 Matni,CS16,Sp18 38

Page 39: Character Functions & Manipulators Arrays in C++...Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Lecture Outline •

5/8/18 Matni,CS16,Sp18 39