Sei sulla pagina 1di 45

Exercise: Structures

1. Product / Inventory Program


a) Create a structure to store information about products for sale in a store. Variables of this type should store information about the product name, the price, and the product number. name: tshirt product number: 3788 price: 15.99 b) rite functions called inputProduct and outputProduct that can be used to !or" !ith this data structure.

c) Create an array of products called Inventory. #dd fi$e products to your in$entory: Example: 1%3 mu& 1.99 1%' pen (.99 1%5 tshirt 19.99 1%) poster 5.99 1%7 "eyrin& 3.99 d) rite a function called outputInventory that outputs the in$entory array. *he array and it+s si,e should be parameters to the function.

e) rite a function called sortInventory that sorts the in$entory by price. -*he in$entory array and si,e should be parameters to the function). .utput the in$entory after!ards to ensure that it is sorted. f) rite a function called priceLookup that has a strin& parameter for the product name, and then returns the price for that product. /f there is no such product in in$entory,the function should return a price of (.

2. Customer

ills

01tend your 2roduct 3/n$entory pro&ram to process customer bills. # bill consists of se$eral items. 0ach item on the customer bill consists of a product name, a 4uantity, and a total. Example: Customer bill 4uantity: 3 name: mu& total: 5.97 4uantity: 1 name: poster total: 5.99 4uantity: 1( name: "eyrin& total: 39.9(

a) Create t!e "ill : 2rompts the user to enter purchase information and creates customer5ill array. *he user should enter a product name and a 4uantity. *he pro&ram should continue promptin& for bill items until the user chooses to end their purchase. b ) #utput t!e "ill: .utput the final bill information in a user friendly !ay. /nclude the total.

Structures are a po!erful data type capable of storin& multiple $alues. 6nli"e arrays, ho!e$er, structures can hold data of multiple types -included nested structures7). 8et+s suppose that !e !ant to store data about people. 0ach person has a name, a !eig!t, and an eye colour. *hese $alues could be stored as a series of simple $ariables 9 a strin& for the name, a double for the hei&ht, and an inte&er code for the eye colour. /f !e !anted to store information for se$eral people, !e could use three arrays 9 one for the names, one for the hei&hts, and one for the eye colour. # better !ay is to use :tructures. e could ha$e a sin&le structure for a 2erson, and then ha$e an array of 2ersons. #ll of the information about a sin&le person could be contained inside one data structure. *he pro&rammer defines a structure as sho!n belo!: struct person <-- structure name ; strin& name< <-- 3 fields: name, eye_color, height int eye$colour< double !eig!t< =< %eclaring &aria"les .nce the structure has been defined, it defines a ne! >type> 9 li"e int or double. ?ou can no! declare $ariables of this type. #ll $ariables of this type !ill ha$e space allocated ->compartments>) for each field. person friend,mother; <--declare 2 variables of type person person teacher; 'ccessing (ields 6se the >dot> notation to access fields of a structure as follo!s: friend.name="Dalia"; friend.height=1.65; cin>>friend.eyecolour; teacher.height= friend.height; cout<<"The teacher's height is " <<teacher.height Structures as )unction Parameters :tructures can be passed to functions @ust li"e any other $ariable. *he structure name is the type of the $ariable. *ypically, !hen !or"in& !ith structures, pro&rammers !rite utility functions to input and output $ariables of this type. -e1. input2erson, output2erson) !oid out"ut#erson $person %hoe!er& '' "arameter a !aria(le of ty"e "erson '' "ur"ose ou"uts the details of this "erson to the screen ) cout << "*ame " << %hoe!er.name << endl; cout << "+ye colour "<<%hoe!er.eyecolour<< endl;

cout << ",eight

" << %hoe!er.height << " metres" << endl;

"erson in"ut#erson$& '' "rom"ts the user to enter information for a "erson '' function returns a "erson ) "erson %hoami; '' local !aria(le cout<<"#lease in"ut a name "; cin.getline$%hoami.name, 1..&; cin.ignore$&; '' discard end of line character cout<<"#lease in"ut an eye colour "; cin>>%hoami.eyecolor&; cout<<"#lease in"ut a height $in m&"; cin>>%hoami.height; return %hoami;

/n the main pro&ram, / could call these functions as follo!s: mother = inputPerson(); '' gets info a(out a "erson, stores in mother cout << " /nfo a(out mother "<<endl; outputPerson(mother); *ixing 'rrays and Structures :tructures can be stored in arrays, and fields of structures can be arrays7 ex 1. "erson 0lass1ist2*345T3D+*T56;<-- array of persons cout << 0lass1ist2.6.name; <-- outputs the name of the first student in array ex 2. struct student ) char name27.6; dou(le mar8s21.6; <-- stores up to 10 numbers in an array field called marks -; '' create a student, and initiali9e mar8s student mario; for $int :=.; :<1.; :;;& mario.mar8s2:6=.; <-- initialize all of Mario's marks to 0 +esting Structures

?ou can define structures !here one of the fiends of the structure is a structure7 # typical e1ample !ould be to ha$e a person structure, !ith an address field, !here the address is another structure. ex. struct address) char street21..6; // street address (number char city21..6; // city char "ro!ince21.6; // province char "ostalcode2<6; // postal code -; struct "erson ) string name; address location; // person's address int age; -; .... "erson sally; cout<< sally.location.city; //outputs sally's city

appartment

street!

. Here is a structure declaration: 1 struct (o: 2) 3 char ma8er2=.6; float height; 4 float %idth; 5 float length; 6 float !olume; 7-; 8 a. Write a function that passes a box structure by alue and that displays the alue of each !e!ber. b. Write a function that passes the address of a box structure and that sets the olu!e !e!ber to the product of the other three di!ensions. c. Write a si!ple pro"ra! that uses these t#o functions. 1 >include <iostream> 2 ''create structure called (o: 3 struct (o: ) 4 char ma8er2=.6; 5 float height; float %idth; 6
float length;

7 8 $ 1 % 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 $ 2 % 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 $ 3 % 3

-;

float !olume;

!oid dis"lay?alues$(o: :&; !oid set?olume$(o: @:&;

''"rototy"e dis"lay?alues func ''"rototy"e set?olume func

int main$& ) (o: firstAo: = )"3haul",1.,B.,15,7...-; structure dis"lay?alues$firstAo:&;

''initiali9e firstAo: ''dis"lay firstAo:

''get user in"ut for dimensions of second (o: structure std cout << "Cn+nter the ma8er a si9e of a (o: to find it's !olume " << std endl; (o: secondAo:; std cout << "4a8er "; std cin.get$secondAo:.ma8er, =.&; std cout << ",eight "; std cin >> secondAo:.height; std cout << "Didth "; std cin >> secondAo:.%idth; std cout << "1ength "; std cin >> secondAo:.length; set?olume$EsecondAo:&; ''use func set?olume to assign a !alue to secondAo:.!olume std cout << "CnThe second (o:'s info is as follo%s Cn"; dis"lay?alues$secondAo:&; ''dis"lay secondAo: !oid dis"lay?alues$(o: :& ) std cout << "4a8er std cout << ",eight std cout << "Didth std cout << "1ength std cout << "?olume ''function to dis"lay all !alues of a (o: struct " << :.ma8er << std endl; " << :.height << std endl; " << :.%idth << std endl; " << :.length << std endl; " << :.!olume << std endl;

!oid set?olume$(o: @:& ''sets the !olume !alue of a (o: struct using l@%@h ) :F>!olume = $:F>height @ :F>length @ :F>%idth&; -

1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 $ 4 % 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 $ 5 %

MODULE 19: C++ FILE I/O 1


&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

'()*+, $: - ./+, /01*2 (*21*2

'y 2rainin" 1eriod: xx hours Note: The examples in this Module we e !ompiled and un usin" Win32 empty console application without #de$ %de$inition& and # ! % esou !e& $iles %'o land(&# )ll p o" am examples ha*e +een tested usin" 'o land C++ ,#xx ONLY# It should +e O- i$ .ou use Win32 empty console application as a ta "et $o othe !ompile s +e!ause heade $iles used a e $ om C++ /tanda d Li+ a .# Fo Linux/Unix0 .ou ha*e to !on!e n a+out the path o di e!to . a!!ess +e!ause o$ the di$$e ent $ile s.stem# 1ou ma. need some !ode modi$i!ation and +een le$t $o .ou assi"nments :o&# 1ou ma. !onside eadin" /e!tion 23#30 4amespa!es $i st0 $o usin" t aditional0 $ull. !omplied C++ o mixin" the C and C++ !odes# Fo C++ and MFC %5indows 6UI p o" ammin"& it is !alled /e iali7ation and the topi!s a e in /in"le Do!ument Inte $a!e %/DI& and Multiple Do!ument Inte $a!e %MDI&# The C standa d $ile input/output is dis!ussed in C File Input/Output# The sou !e !ode $o this Module is C++ File I/O sou !e !odes# The C++ file input/output programming skills:

*nderstand and use the ifstrea!3 ofstrea! and fstrea! class ob4ects. *nderstand and use a se5uential access file 6 7ead and Write !e!ber functions. *nderstand and use a rando! access file 6 7ead and Write !e!ber functions. 8e fa!iliar #ith other file /9( !e!ber functions.

!"

#ntro$uction The idea a+out the st eam has +een explained extensi*el. in C $ile I/O and C++ $o matted I/O also has +een explained in C++ Fo matted I/O# ) $ile 8ust a !olle!tion o$ elated data that t eated +. C++ as a se ies o$ +.tes# '. the wa.0 st eams mo*e in one wa. and in se ial $ashion $ om e!ei*e and sende # Othe than $iles on dis90 de*i!es su!h as ma"neti! tapes0 p ima . o se!onda .

sto a"e de*i!es0 p inte s and netwo 9s that !a .in" data a e also t eated as $iles# File I/O is one o$ the inte estin" topi!s in C / C++ +e!ause o$ the wide appli!ations# 5e need to w ite to dis9 when we do so$twa e installation0 w itin" windows e"ist .0 ead0 w ite0 delete0 update $ile !ontents0 sendin" and e!ei*in" data th ou"h netwo 9s %so!9ets& et!# The in!lude $iles needed in o de to use the dis9 $ile I/O !lass o+8e!ts a e: :iost eam; and :$st eam;# iost eam !ontains standa d input output o+8e!ts su!h as !in0 !out0 !e and !lo" % e$e to C++ Fo matted I/O&# -eep in mind that new heade $iles whi!h a e $ull. C++ standa d !omplian!e that usin" template +ased heade $iles %I/O/IEC C++& don<t ha*e the "h an.mo e# 1ou !an ead the sto . in 4amespa!es# Fu the mo e same as in C File I/O0 all the p o" am examples don<t !onside the $ile a!!ess pe missions# 4o mall.0 $ile a!!ess pe missions a e !om+ined with the use pe missions and i"hts as se!u it. $eatu es o$ the Ope atin" /.stems# The. a e implementation dependant and the dis!ussion !an +e $ound in 5indows 5in32 p o" ammin" tuto ial# Fo C++0 all $ile o+8e!ts +elon" to the one o$ the $ollowin" !lasses: %rief $escription O+8e!ts +elon" to this !lass a e asso!iated with $iles opened $o input pu poses# o$st eam O+8e!ts +elon" to this !lass a e asso!iated with $iles opened $o output pu poses# O+8e!ts +elon" to this !lass a e asso!iated with $iles opened $o input and output pu poses# Ta+le 19#1: File input/output !lasses# These !lasses a e de$ined in :$st eam; heade $ile# Data $iles a e atta!hed with $iles o+8e!ts usin" the open%& mem+e $un!tion o$ the $ile o+8e!t# The open%& p otot.pe is: *oid open%!onst !ha =name0 int mode0 int a!!ess&> 5he e: 1# name is the $ilename# 2# Open $ile modes %$la"s& a e used to indi!ate what to do to the $ile %e#"# open0 !lose& and the data %e#"# ead0 w ite&# The $la"s !an +e lo"i!all. O?ed# Mode must +e one o$ the $ollowin": 'escription )ppend data to the end o$ the output $ile# 6o to the end o$ the $ile when open# Open $o input0 with open%& mem+e $un!tion o$ the i$st eam *a ia+le# Open $o output0 with open%& mem+e $un!tion o$ the o$st eam *a ia+le# 'ina . $ile0 i$ not p esent0 the $ile is opened as an )/CII $ile as de$ault# Dis!a d !ontents o$ existin" $ile when openin" $o w ite# Fail i$ the $ile does not exist# Fo output $ile onl.0 openin" an input $ile alwa.s $ails i$ the e is no $ail# Do not o*e w ite existin" $ile# I$ a $ile exists0 !ause the openin" $ile to $ail#

&o$e s::app s::ate s::in s::out s::+ina . s::t un! s::no! eate s::no epla!e

Ta+le 19#2: File open modes 3# File p ote!tion a!!ess dete mines how the $ile !an +e a!!essed# It is Ope atin" /.stem dependent and the e a e othe s att i+utes that a e implementation extensions# Fo DO/( example0 it must +e one o$ the $ollowin": (ttri)utes @ 1 2 C 'escription 4o mal $ile o ) !hi*e ?eadAonl. $ile Bidden $ile /.stem $ile

Ta+le 19#3: File t.pes To de!la e the input $ile st eam i#e# $o eadin" we would de!la e li9e this: i$st eam theinputfile> To de!la e the output $ile st eam i#e# $o w itin" we would de!la e li9e this: o$st eam theoutputfile> Then0 to !onne!t to a st eam0 let sa. openin" $ile test$ileio#dat $o eadin"0 the $ile whi!h lo!ated in the same $olde as the exe!uta+le p o" am we would w ite li9e this: theinputfile#open%Dtest$ileio#dat D&> O with the path we !ould w ite: theinputfile#open%D!:EEtest$ileio#dat D&> 4ext0 openin" a $ile $o eadin" and +ina . t.pe modes0 we !ould w ite: theinputfile#open%Dtest$ileio#dat D0 ios::in F ios::+ina .&> )nothe example0 openin" a $ile $o eadin"0 with no mal t.pe a!!ess and "o to the end o$ the $ile0 we !ould w ite li9e this: theinputfile#open%Dtest$ileio#dat D0 ios::in F ios::ate0 @&> Fo w itin"0 to !onne!t to a st eam0 let sa. openin" $ile test$ileio#dat $o w itin"0 the $ile whi!h lo!ated in the same $olde as the unnin" p o" am# G e*ious !ontent o$ the test$ileio#dat will +e o*e w itten0 we !ould w ite li9e this: theoutputfile#open%Dtest$ileio#datD&> O with the path: theoutputfile#open%D!:EEtest$ileio#dat D&> Then0 openin" a $ile $o w itin" and appendin" at the end o$ the $ile modes0 we !ould w ite li9e this: theoutputfile#open%Dtest$ileio#datD0 ios::out F ios::app&> O openin" $o w itin"0 !he!9 the existin" o$ the $ile with no mal a!!ess modes0 we !ould w ite li9e this: theoutputfile#open%Dtest$ileio#datD0 ios::out F ios::no! eate0 @&> )$te we ha*e !ompleted the $ile p o!essin"0 we ha*e to !lose o dis!onne!t the st eam to $ ee up the esou !es to +e used +. othe p o!esses o p o" ams# Usin" the !lose%& mem+e $un!tion0 $o input st eam we would w ite li9e this: theinputfile#!lose%&> )nd $o output st eam: theoutputfile#!lose%&>

Du in" the openin" $o eadin" o w itin"0 we should p o*ide e o handlin" outines to ma9e su e the $ile ope ations ha*e !ompleted su!!ess$ull. othe wise some e o messa"e should +e displa.ed o e o handlin" outines +een exe!uted# Fo example we !an use $ail%& mem+e $un!tion: Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I i$st eam input$ile> input$ile#open%Dtest$ileio#datD&> i$%input$ile#$ail%&& I !out::DThe $ile !ould not +e openedJEnD> exit%1&> // @ K no mal exit0 non 7e o K some e o L ### O +ad%& with !e # i$%input$ile#+ad%&& I !e ::DUna+le to open test$ileio#datEnD> exit%1&> // @ K no mal exit0 non 7e o K some e o L The $ollowin" examples ! eated $o 5in32 empt. !onsole appli!ation without #de$ %de$inition& and # ! % esou !e& $iles# )ll examples in this Module ha*e +een tested usin" 'o land ,#xx O4L1# )t the end o$ this Module0 the e a e p o" am examples !ompiled with MC+ +/MC++ #4et and "++ $o Linux# -eep in mind that in Mi! oso$t 5indows ope atin" s.stem en*i onment the e a e anothe la.e o$ se!u it. $o a!!essin" 5indows o+8e!ts# The in$o mation o$ the 5indows se!u it. $eatu es !an +e $ound in 5in32 /D- do!umentation# This Module will onl. dis!uss $ile input/output in "ene al $ om C++ p o" ammin" pe spe!ti*e# Fi stl.0 ! eate a $ile named samplerea$"t*t at oot on C: d i*e %o othe lo!ation p o*ided .ou expli!itl. state the $ull path in the p o" am&# 5 ite some text as shown +elow in samplerea$"t*t $ile and sa*e it# This is $ile sample ead#txt# This $ile will +e opened $o eadin" then its !ontent will +e w itten to anothe $ile and standa d output i#e s! een/!onsole###a$te .ou ha*e exe!uted this C++ p o" am0 without e o ####this text should +e output on .ou s! een as well as w itten to the samplew ite#txt $ile# DonNt $o "et to !he!9 the !ontent o$ the samplew ite#txt#

sample ead#txt $ile !ontent // eadin" $ om a*aila+le $ile !ontent // then w itin" the !ontent to anothe // $ile# Fi stl.0 ! eate $ile $o eadin" %!an in!lude path& // let sa.s DC:Esample ead#txtD0 at oot on C d i*e# // T.pe some text as shown0 then exe!utes this p o" am# Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> // $un!tion de$inition0 to open $ile $o eadin"### *oid openin$ile%i$st eam Oin$ile& I !ha $ilenameP1@@Q> !out::DEnte the $ile name: D> // Ente the $ilename that .ou ha*e ! eated // %!an in!lude path&# F om the !omment a+o*e // .ou ha*e to ente DC:Esample ead#txtD without the dou+le Ruotes# !in;;$ilename> in$ile#open%$ilename&> L *oid main%*oid& I // de!la e the input $ile st eam i$st eam input$ile> // de!la e the output $ile st eam o$st eam output$ile> !ha !hs> // $un!tion !all $o openin" $ile $o eadin"### openin$ile%input$ile&> // ! eate0 i$ not exist and open it $o w itin" output$ile#open%DC:EEsamplew ite#txtD&> // test until the end o$ $ile while %Jinput$ile#eo$%&& I // ead !ha a!te until end o$ $ile input$ile#"et%!hs&> i$ %Jinput$ile#eo$%&& I // output !ha a!te +. !ha a!te %+.te& on s! een0 standa d output

!out::!hs> // w ite to output $ile0 samplew ite#txt output$ile::!hs> L L !out::DEn?eadin" and w itin" $ile is !ompletedJD::endl> // !lose the input $ile st eam input$ile#!lose%&> // !lose the output $ile st eam output$ile#!lose%&> L Output:

In this p o" am we do not p o*ide e o handlin"s0 the existin" $ile to +e opened is not *e i$ied# )nothe example usin" "etline%& mem+e $un!tion# Fi stl. ! eate text $ile0 named rea$file"t*t0 put it on d i*e C: 5indows0 then t.pe the $ollowin" sample text and sa*e it# This is ead$ile#txt# Sust sample text0 openin" $o eadin" +. usin" "etline%& mem+e $un!tion# The e a e $ou lines o$ text to +e ead $ om# This is 8ust plain simple eadin" text $ om a $ile# // usin" "etline%& mem+e $un!tion Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I !ha $ilenameP,@Q> i$st eam input$ile> !ha Fi stLineP,@Q> !ha /e!ondLineP,@Q> !ha Thi dLineP,@Q>

// p ompt use $o $ile name to +e opened### !out::DEnte the $ilename to +e opened: D> !in;;$ilename> // test open $ile $o eadin"### input$ile#open%$ilename&> // i$ not the end o$ $ile0 do### i$%Jinput$ile#eo$%&& I !out::DEnThe $i st line o$ text is: EnD> input$ile#"etline%Fi stLine0 ,@&> !out::Fi stLine::NEnN> !out::DThe se!ond line o$ text is: EnD> input$ile#"etline%/e!ondLine0 ,@&> !out::/e!ondLine::endl> !out::DThe thi d line o$ text is: EnD> input$ile#"etline%Thi dLine0 ,@&> !out::Thi dLine::endl> L L Output:

)nothe p o" am example with a simple ex!eption handlin"# // a simple $ile Tex!eption handlin"< when openin" $ile $o eadin"# // The e is no test$ileio#txt at the oot o$ d i*e C at the +e"innin"# Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I !ha $ilenameP Q U DC:EEtest$ileio#txtD> i$st eam input$ile> input$ile#open%$ilename0 ios::in&> // test i$ $ail to open $ail $o eadin"0 doV

i$%input$ile#$ail%&& I !out::DOpenin" D::$ilename::D $ile $o eadin"EnD> !out::DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEnD> !out::DThe D::$ilename::D $ile !ould not +e openedJEnD> !out::DGossi+le e o s:EnD> !out::D1# The $ile does not exist#EnD> !out::D2# The path was not $ound#EnD> s.stem%DpauseD&> exit%1&> // 8ust exit // @Ano mal0 non 7e o A some e o L // i$ su!!ess$ul openin" $ile $o eadin"0 doV else I !out::DThe D::$ilename::D $ile was opened su!!ess$ull.JEnD> !out::DEnDo some $ile p o!essin" he e###EnD> L input$ile#!lose%&> // test i$ $ail to !lose the $ile0 doV i$%input$ile#$ail%&& I !out::DEnThe $ile D::$ilename::D !ould not +e !losedJEnD> s.stem%DpauseD&> exit%1&> L // else0 doV else !out::DEnThe D::$ilename::D $ile was !losed su!!ess$ull.JEnD> L Output:

Then0 ! eate $ile named testfileio"t*t on d i*e C:# ?eA un the p o" am0 the $ollowin" should +e output#

/ame outine !an +e use $o $ile output o$st eam0 +. epla!in" the i$st eam o+8e!ts# The $ollowin" example shows .ou how to p ompt use $o the $ile name# // p omptin" use $o $ilename to +e opened othe s should +e // same as the p e*ious example# Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I !ha $ilenameP1@@Q> i$st eam input$ile> // p omptin" use $o $ilename to +e openedV // in!ludin" the $ull path i$ ne!essa .V // e#"# !:Etest$ileio#txt0 !:E5indowsETempEtest$ile#txt et! !out::DEnte the $ile name to +e opened: D> // sto e at an a a. $ilename### // a a. without P Q is a pointe to the // $i st a a.<s element### !in;;$ilename> // opened the $ile $o input### input$ile#open%$ilename0 ios::in&> // test i$ $ail to open $ile $o eadin"0 doV i$%input$ile#$ail%&& I !out::DOpenin" D::$ilename::D $ile $o eadin"EnD> !out::DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEnD> !out::DThe D::$ilename::D $ile !ould not +e openedJEnD> !out::DGossi+le e o s:EnD> !out::D1# The $ile does not exist#EnD> !out::D2# The path was not $ound#EnD> exit%1&> // 8ust exit // @Ano mal0 non 7e o A some e o L // i$ su!!ess$ul openin" $ile $o eadin"0 doV else I

!out::DThe D::$ilename::D $ile was opened su!!ess$ull.JEnD> !out::DEnDo some $ile p o!essin" he e###EnD> L // !lose $ile $o inputV input$ile#!lose%&> // test i$ $ail to !lose the $ile0 doV i$%input$ile#$ail%&& I !out::DEnThe $ile D::$ilename::D !ould not +e !losedJEnD> exit%1&> L // else0 doV else !out::DEnThe D::$ilename::D $ile was !losed su!!ess$ull.JEnD> L // tested usin" the win32 !onsole mode######## // p o*ided the $ile test$ileio#txt exists on the C: d i*eV Output:

!"2 +e,uential -ile .rocessing ?eadin" data and do some !al!ulation0 then displa. the data# Fi stl.0 ! eate a $ile named testfileio "t*t on d i*e C:# -e. in some data in this test $ile as shown +elow and sa*e the $ile# 1@@#23 ,W#33 WX#12 Y9#1@ ,,#C, 23#12 ,W#11 C3#2C W,#32 C,#@@ C eate and un the $ollowin" p o" am# // a simple p o!essin" data $ om exte nal $ile# // ead the data in seRuential mode0 do some // !al!ulation and displa. to the standa d output# // C eate $ile test$ileio1#txt on d i*e C0 and t.pe some data as shown Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I

!ha $ilenamePQ U DC:EEtest$ileio1#txtD> i$st eam input$ile> // openin" input $ile $o eadin" input$ile#open%$ilename0 ios::in&> // test i$ $ail to open the $ile0 doV // e o handlin" $o $ile openin" i$%input$ile#$ail%&& I !out::DOpenin" $ile D::$ilename::D $o eadin"EnD> !out::DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEnD> !out::DThe $ile !ould not +e openedJEnD> !out::DGossi+le e o s:EnD> !out::D1# The $ile does not exist#EnD> !out::D2# The path was not $ound#EnD> s.stem%DpauseD&> exit%1&> // 8ust exit // @Ano mal0 non 7e o A some e o L // i$ su!!ess$ul0 do the $ollowin"### else I !out::DThe D::$ilename::D $ile was opened su!!ess$ull.JEnD> // de!la e some *a ia+les $o simple !al!ulation $loat p i!e0 total U @> int !ount U @> !out::D?eadin" data and do some !al!ulationEnEnD> // ead data $ om input st eam### input$ile;;p i!e> // test0 i$ end o$ $ile not $ound0 do the $ollowin"### while%Jinput$ile#eo$%&& I // total U total + p i!e total +U p i!e> !ount++> !out::DItem p i!e H D::!ount::D is D::p i!e::endl> // eA ead the next item p i!e within the loop input$ile;;p i!e> L !out::DThe total p i!e $o D::!ount::D items is: D::total::endl> !out::DEnAAAAAAADO4EAAAAAAAEnD::endl> // !lose the input $ile input$ile#!lose%&> // test !losin" $ile0 i$ $ail to !lose the $ile0 do### // e o handlin" $o $ile !losin"

i$%input$ile#$ail%&& I !out::DThe D::$ilename::D $ile !ould not +e !losedJEnD> // somethin" w on"0 8ust exit### exit%1&> L // i$ su!!ess$ul !lose the $ile0 do#### else !out::DThe D::$ilename::D $ile was !losed su!!ess$ull.JEnD> L L Output:

4ow let t . usin" the ost eam !lass o+8e!t# This will ! eate and open a $ile $o w itin"# The $ile will +e ! eated i$ it does not exist .et# // a simple p o!essin" data $ om exte nal $ile# // C eatin"0 openin" and w itin" some data in $ile // and appendin" data at the end o$ $ile### Hin!lude :iost eam; Hin!lude :$st eam; usin" namespa!e std> *oid main%*oid& I !ha $ilenameP Q U DC:EEtest$ileio2#txtD> o$st eam output$ile> // ! eatin"0 openin" and w itin"/appendin" data to $ile output$ile#open%$ilename0 ios::outFios::app&> // simple e o handlin" $o $ile ! eatin"/openin" $o w itin" // test i$ $ail to open the $ile0 doV

i$%output$ile#$ail%&& I !out::DC eatin" and openin" $ile D::$ilename::D $o w itin"EnD> !out::DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEnD> !out::DThe D::$ilename::D $ile !ould not +e ! eated/openedJEnD> !out::DGossi+le e o s:EnD> !out::D1# The $ile does not exist#EnD> !out::D2# The path was not $ound#EnD> exit%1&> // 8ust exit // @Ano mal0 non 7e o A some e o L // else0 i$ the $ile !an +e opened0 doV else I !out::DThe D::$ilename::D $ile was ! eated and opened su!!ess$ull.JEnD> !out::DEnDo some $ile w itin"####EnEnD> output$ile::D5 itin" some data in this $ileEnD> output$ile::DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEnD> !out::DChe!9 the D::$ilename::D $ile !ontents :A&D::endl> !out::DI$ the $ile al ead. ha*e had data0 the new data will +e appendedEnD> int sampledata> // w ite some inte"e s to the $ile### $o %sampledataU@> sampledata:U1@> sampledata++& output$ile::sampledata::D D> output$ile::endl> // !lose the output $ile output$ile#!lose%&> // test i$ $ail to !lose the $ile0 do the $ollowin"### // simple e o handlin" $o output $iles !losin" i$%output$ile#$ail%&& I !out::DThe D::$ilename::D $ile !ould not +e !losedJEnD> exit%1&> L // test i$ su!!ess$ul to !lose the $ile0 do the $ollowin"### else !out::DEnThe D::$ilename::D $ile was !losed su!!ess$ull.JEnD> L L Output:

The !ontent o$ the testfileio2"t*t is as $ollows: 5 itin" some data in this $ile AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @ 1 2 3 C , W X Y 9 1@ 5hen .ou e un this p o" am se!ond times0 the data will +e appended at the end o$ the pe *ious data# 5 itin" some data in this $ile AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @ 1 2 3 C , W X Y 9 1@ 5 itin" some data in this $ile AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @ 1 2 3 C , W X Y 9 1@

n an ) a. wo 9sheet we had $ou "ame s!o e $ om $ou di$$e ent pla.e s0 whi!h we ead and p inted in e*e se o de # Instead o$ de$inin" /!o e10 /!o e20 /!o e3 and /!o eC0 we de$ined one a a. that held all $ou s!o es0 that is /!o ePCQ# 5e " ouped them in an a a. +e!ause all items we e o$ the same $ata type and had a simila meanin"0 the. we e all "ame s!o es# Bowe*e what a+out the " oup o$ data items that a e elated +ut ha*e $ifferent $ata typesZ Fo example0 suppose that alon" with the "ame s!o es0 we want to sto e the name o$ ea!h pla.e 0 the !ount . $ om whi!h the. !ome and thei a"es# Be e0 the s!o e is a $loat0 the pla.e and the !ount . a e !ha a!te st in"s and the a"e is an inte"e # 5e would li9e to sto e these $ou items to"ethe as one unit and to handle and p o!ess them to"ethe as a " oup# In o de to do this we !an use structure $ata type# The 9e.wo d use to de$ine this data t.pe is struct# Fo ou needs0 we !an de$ine the st u!tu e as shown +elow#

st u!t Ga ti!ipant I !ha 4ameP2@Q> !ha Count .P2,Q> $loat /!o e> int )"e> L> st u!t is a 9e.wo d and the Ga ti!ipant is a name o ta" that we p o*ided# )ll that we a e doin" is de$inin" a st u!tu e !alled st u!t Ga ti!ipant# 5e a e not ! eatin" a *a ia+le instead we a e ! eatin" a ne/ $ata type that in!ludes o a"" e"ate othe C and C++ data t.pes# 1ou !an thin9 o$ this as a st u!tu e template $ om whi!h st u!tu e *a ia+les ma. +e de$ined# )n. *a ia+le de!la ed as +ein" o$ this t.pe will ha*e these $ou pa ts that a e !alled mem)ers of the structure# Late in the C++ wo 9sheet o$ this se ies we will add mo e $eatu es to st u!tu e templates and !all them classes# 0aria)les de$ined as !lasses will +e !alled o)1ects# Sust as *a ia+les a e ! eated $ om data t.pes o st u!tu e *a ia+les a e ! eated $ om st u!tu e de$initions0 o)1ects are create$ from classes# 5ith a a.s0 we need to spe!i$. the su+s! ipt o the index to a!!ess one item inside the a a.# To a!!ess one item in a st u!tu e0 we need to spe!i$. the name of the mem)er# The o de in whi!h the st u!tu e mem+e s a e de$ined is not impo tant# The $ollowin" !ode shows how st u!tu e *a ia+les a e de$ined and initiali7ed# st u!t Ga ti!ipant Gla.e 10 Gla.e 2 U ID-o eaD0 D-en.aD0 C#W0 19L> The $ollowin" Fi"u es t . to show the de$inin" two st u!tu e *a ia+les#

Gla.e 1 is de$ined and has $ou mem+e s# Gla.e 2 is also de$ined and its $ou mem+e s a e initiali7ed# Be e0 the o de is impo tant# The. should +e initiali7ed in the same o de that the st u!tu e mem+e s a e de$ined as shown in the a+o*e Fi"u e# In data+ase te minolo".0 a mem+e o$ a st u!tu e *a ia+le is !alled a fiel$0 a st u!tu e *a ia+le with its data is !alled a $ata)ase recor$ and a !olle!tion o$ elated e!o ds is !alled a file# 5ith a a.s0 we spe!i$. the su+s! ipt o an index en!losed in + a!9ets to a!!ess one element# 5ith st u!tu es0 we must $ollow the *a ia+le name +. a perio$0 $ollowed +. the mem+e name to a!!ess one mem+e # Fo example0 Gla.e 2#/!o e is eRual to C#W@# The $ollowin" !ode: st !p.%Gla.e 1#Count .0 Gla.e 2#Count .&> will !op. the !ount . %*alue& o$ Gla.e 2 as the !ount . o$ Gla.e 1# )dditionall.0 while Gla.e 2#Count . is eRual to the st in" [-en.a\0 Gla.e 2#Count .P3Q is eRual to the !ha a!te T.<# 5e !an alwa.s w ite an a a. o$ pla.e s li9e the $ollowin"# st u!t Ga ti!ipant Gla.e P2Q> This will ! eate an a a. !alled Gla.e P Q with onl. 2 slots0 whe e ea!h slot is a st u!tu e o$ t.pe st u!t Ga ti!ipant# /ee the $ollowin" Fi"u e that t . to depi!t an a a. o$ st u!tu e#

To ead in the name $o the pla.e in slot 20 the statement will loo9 li9e this:

// s!an$%D]s0 OGla.e P@Q#4ame&> s!an$^s%D]s0 OGla.e P@Q#4ame0 2@&> The O is optional he e +e!ause as .ou ha*e lea ned p e*iousl.0 a a. names a e a!tual add esses an.wa.# 5e !an also ! eate a st u!tu e +ased on othe st u!tu es# Conside the the $ollowin" !ode example# st u!t Team // de$inin" a new st u!tu e I st u!t Ga ti!ipant Captain> // st u!t Team !ontains a st u!tu e int 5ins> int Losses> st u!t Ga ti!ipant Gla.e P2Q> // st u!t Team has an a a. o$ st u!tu es L> // de$inin" and initiali7in" a *a ia+le st u!t Team /weetThin"s U I IDSasmineD0 DCam+odiaD0 3#,0 22L0 ,0 20 IIDMi!haelD0 DMexi!oD0 ,#20 2@L0 IDLeona dD0 D6e man.D0 C#@0 2CLL // need the oute + a!es L> // 8ust de$inin" a *a ia+le st u!t Team ?owd.'a+ies> In the $ollowin" Fi"u e0 .ou !an see what the *a ia+le /weetThin"s loo9s li9e0 a st u!tu e o$ st u!tu es#

I$ we want to !op. the !ontents o$ /weetThin"s to ?owd.'a+ies0 all we need to do is: ?owd.'a+ies U /weetThin"s> Bowe*e 0 $o the sa9e o$ o+tainin" expe ien!e in handlin" st u!tu es0 let us do the same thin" the lon" wa.# // !op. the Captain *alues st !p.%?owd.'a+ies#Captain#4ame0 /weetThin"s#Captain#4ame&> st !p.%?owd.'a+ies#Captain#Count .0 /weetThin"s#Captain#Count .&> ?owd.'a+ies#Captain#)"e ?owd.'a+ies#Captain#/!o e U /weetThin"s#Captain#)"e> U /weetThin"s#Captain#/!o e>

// !op. the Gla.e *alues $o %i U @> i :U 1> ++i& I st !p.%?owd.'a+ies#Gla.e PiQ#4ame0 /weetThin"s#Gla.e PiQ#4ame&> st !p.%?owd.'a+ies#Gla.e PiQ# Count .0 /weetThin"s#Gla.e PiQ#Count .&>

?owd.'a+ies#Gla.e PiQ#)"e U /weetThin"s#Gla.e PiQ#)"e> ?owd.'a+ies#Gla.e PiQ#/!o e U /weetThin"s#Gla.e PiQ#/!o e> L // Cop. the 5ins and Losses ?owd.'a+ies#5ins U /weetThin"s#5ins> ?owd.'a+ies#Losses U /weetThin"s#Losses> 1ou !an see that0 althou"h the $i st solution is onl. one statement0 the expanded solution illust ates how to handle indi*idual mem+e s o$ st u!tu es# 4ow let us ta9e a simple st u!tu e and use it to illust ate how st u!tu es a e used with $un!tions# 5e will do this +. w itin" the enti e p o" am# In the $ollowin" p o" am example0 we de$ine st u!t Mo+ile# It is simpl. made up o$ two mem+e s: one is !alled Ma9eP Q and the othe is 1ea # The st u!tu e is de$ined outside an. $un!tion0 so it is a*aila+le "lo+all. to all $un!tions# main%& de$ines Ca 1 and Ca 2 o$ t.pe st u!t Mo+ile# Then main%& !alls the $un!tion Find1ea %& +. passin" one !ha a!te st in" with a *alue o$ [Fo d\# Exe!ution then "oes to that $un!tion# In Find1ea %&0 the !ha a!te st in" is !alled 4ameP Q# ) lo!al *a ia+le o$ t.pe st u!t Mo+ile is de$ined with the name o$ Ca # Find1ea %& as9s $o the .ea o$ the !a "i*en +. 4ameP Q and eads in the .ea mem+e o$ Ca # The ma9e mem+e o$ Ca is assi"ned the st in" in 4ameP Q# Then Find1ea %& etu ns the name and the .ea o$ the !a as t.pe st u!t Mo+ile# This st u!tu e is assi"ned to Ca 1 in main%&# /imila l.0 the st in" [Mustan"\ is passed to Find1ea %&0 whi!h etu ns that st in" and its .ea +a!9 to main%& as a st u!t Mo+ile# This new st u!tu e is assi"ned to Ca 2# 4ow main%& !alls the $un!tion G intOldest%&# Instead o$ passin" a st in"0 main%& passes two st u!tu es# )lso0 instead o$ assi"nin" the $un!tion to a *a ia+le li9e Ca 1 and Ca 20 main%& doesn<t assi"n G intOldest%& to an.thin"# Ben!e0 the e is no etu n in G intOldest%& and its etu n data t.pe is *oid# G intOldest%& ma9es a !op. o$ these two st u!tu es into )uto1 and )uto2# I$ this $un!tion had !han"ed the !ontents o$ these st u!tu es0 the !han"es would not +e e$le!ted in Ca 1 and Ca 2 in main%&# This is li9e s!ala s and unli9e a a.s# The $un!tion p o!eeds to $ind the oldest o$ the two !a s and p ints its ma9e# 4ote that the e is no etu n statement he e# Hin!lude :stdio#h; Hin!lude :st in"#h; // 6lo+al de$inition st u!t Mo+ile I !ha Ma9eP2@Q> int 1ea > L> AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

// $un!tion p otot.pe with st u!tu e etu n t.pe st u!t Mo+ile Find1ea %!ha 4ameP Q&> // $un!tion p otot.pe with st u!tu es a "uments passed *oid G intOldest%st u!t Mo+ile )uto10 st u!t Mo+ile )uto2&> *oid main%*oid& I st u!t Mo+ile Ca 10 Ca 2> Ca 1 U Find1ea %DTo.otaD&> Ca 2 U Find1ea %DMustan"D&> G intOldest%Ca 10 Ca 2&> L // this $un!tion e!ei*es one st in" that is the ma9e o$ a !a 0 // eads in its .ea and etu ns them +oth as Dst u!t Mo+ileD st u!t Mo+ile Find1ea %!ha 4ameP Q& I st u!t Mo+ile Ca > p int$%D5hat .ea is the ]sZ D0 4ame&> // s!an$%D]dD0 OCa #1ea &> s!an$^s%D]dD0 OCa #1ea 0 1&> p int$%DCa #1ea U ]dEnD0 Ca #1ea &> // st !p.%Ca #Ma9e0 4ame&> st !p.^s%Ca #Ma9e0 si7eo$%Ca #Ma9e&0 4ame&>

etu n Ca > L // this $un!tion e!ei*es two st u!tu es o$ t.pe Dst u!t Mo+ileD // and p ints the .ea o$ the oldest !a # It etu ns nothin"# *oid G intOldest%st u!t Mo+ile )uto10 st u!t Mo+ile )uto2& I i$%)uto1#1ea : )uto2#1ea & p int$%DThe oldest !a is the ]sEnD0 )uto1#Ma9e&> else i$%)uto1#1ea ; )uto2#1ea & p int$%DThe oldest !a is the ]sEnD0 )uto2#Ma9e&> else p int$%DThe. a e +oth the same a"eJEnD&> L struct 'ata Type .ractices 1# Let us int odu!e two new $un!tions intended $o st in"s# 1ou ma. ente [1ou< e ma9in" me +lue\ and then ente [)ll m. lo*in"\# /how the output and answe the Ruestions# Hin!lude :stdio#h; *oid main%& I !ha aP2,Q0 +P2,Q> puts%D4ame .ou $a*o ite son" title: D&> // "ets%a&>

a# +# !# d# e#

Onl. the $i st wo d# The enti e st in"# The $i st etu n that was ente ed# 1es it did# O$ !ou se "ets%&/"ets^s%&#

"ets^s%a0 2,&> puts%DEn4ame anothe son" title:D&> // s!an$%D]sD0 O+&> s!an$^s%D]sD0 O+0 2,&> p int$%DEna U ]s0 + U ]sEnD0 a0 +&> L a# 5as the s!an$^s%& a+le to ead the enti e st in" o onl. the $i st wo dZ +# 5as the "ets^s%& a+le to ead the enti e st in" o onl. the $i st wo dZ !# Did the "ets^s%& stop eadin" at the $i st spa!e o the $i st etu n that was ente edZ d# Did the puts%& add a TEn< at the end o$ the st in" that is p intedZ e# 5hi!h $un!tion would .ou p e$e to ead in a st in"0 s!an$^s%& o "ets^s%&Z 2# Fi stl.0 ente [Ooowee 'a+e\ and then 2#C@ $o the $ollowin" p o" am# /how the output and answe the Ruestions# Hin!lude :stdio#h; *oid main%& I // de$inition o$ st u!tu e st u!t /on" I !ha 4ameP2,Q> $loat Len"th> L> // end o$ de$inition

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

a# +# !# d# e#

!ha and $loat# 4ame and Len"th# The. allo!ate spa!e in memo .# 1es it ! eates in itsel$ a new *a ia+le# 1es#

// *a ia+le de!la ation st u!t /on" Title1> p int$%DThe si7e o$ Title1 st u!tu e *a ia+le is ]d +.tes#EnD0 si7eo$%Title1&&> puts%D4ame .ou $a*o ite son" title: D&> "ets^s%Title1#4ame0 2,&> puts%DBow lon" is itZD&> s!an$^s%D]$D0 OTitle1#Len"th&> p int$%DEn1ou son" is D&> puts%Title1#4ame&> p int$%D)nd it is ]#2$ min# lon"#EnD0 Title1#Len"th&> L

$# Title1# "# It has two pa ts named name and len"th#

h# ### i# 4o# st u!tu e !an ha*e di$$e ent data t.pes# 8# 5e use a dot ope ato and the st u!tu eNs mem+e name# 9# Title1#Len"th U @> l# Title1#4ame U [M # Moonli"htin"\#

Sust as the int and $loat a e data t.pes0 st u!t /on" is a new data t.pe that we ha*e de$ined# a# 5hat a e the two 9nown t.pes used to de$ine st u!t /on"Z +# st u!t /on" is de$ined with two mem+e s# 5hat a e thei namesZ !# Do the wo ds !ha o $loat +. themsel*es ! eate new *a ia+les o allo!ate spa!e in memo .Z d# /in!e st u!t /on" is also a

e# $#

"#

h# i#

8#

9# l#

new data t.pe0 do .ou thin9 that it ! eates in itsel$ a new *a ia+leZ Is a semi!olon used at the end o$ the st u!tu e de$initionZ /in!e the de$inition o$ the st u!tu e doesn<t ! eate a new *a ia+le0 what is the name o$ the *a ia+le de!la ed usin" the st u!t /on" data t.peZ Title1 is a new *a ia+le that ta9es up spa!e in memo .# Bow man. pa ts does it ha*eZ 5hat a e thei namesZ /how the !ontents o$ ea!h mem+e inside the +ox Title1# )n a a. is a collection of many items of the same $ata type0 su!h as int o !ha # /imila l.0 a st u!tu e data t.pe is a !olle!tion o$ man. items# Do the. ha*e to +e o$ the same data t.peZ 5hen a!!essin" a slot in an a a.0 a set o$ + a!9ets is used0 su!h as aP2Q U @># 5hen we want to a!!ess a mem+e o$ a st u!tu e0 what do we useZ Bow would .ou ha*e assi"ned the Len"th mem+e o$ Title1 to @Z Bow would .ou ha*e assi"ned the name mem+e o$ Title1 to [M # Moonli"htin"\Z

3# In the $ollowin" p o" am example ente [?ide s on the /to m\ and 3#1@ $o the sample input data# /how the output and answe the Ruestions# Hin!lude :stdio#h; Hin!lude :st in"#h; *oid main%& I st u!t /on" I !ha 4ameP2,Q> $loat Len"th> L> st u!t /on" Title10 Title2> st !p.^s%Title2#4ame0 2,0 DM. Tea d opsD&> Title2#Len"th U 2#3,$> puts%D4ame .ou $a*o ite son":D&> "ets^s%Title1#4ame0 2,&> puts%DBow lon" is itZD&> s!an$^s%D]$D0 OTitle1#Len"th&> p int$%DEnM. son" is ]sEn 1ou son" is D0 Title2#4ame&> puts%Title1#4ame&> p int$%D1ou s is ]#2$ min# lon"e EnD0 Title1#Len"th A Title2#Len"th&> L a# Can .ou p int out +oth mem+e s o$ Title2 without spe!i$.in" the mem+e names as shown +elowZ Does this wo 9Z p int$%D]s ]#2$EnD0 Title2&> +# Can .ou assi"n Title2 to Title1 a# 4o0 we !anNt and this doesnNt wo 9# 5e need the name o$ the mem+e # +# 1es we !an and it does wo 9 p o*ided that the. +oth ha*e same st u!tu e as in this example# Be e we assi"n the whole st u!tu e# !# It doesnNt wo 9# 5e !annot assi"n the *alue o$ Title2#4ame di e!tl. to Title1#4ame +ut we !an !op. the *alue as the $ollowin" !ode: st !p.^s%Title1#4ame0 2,0 Title2#4ame&>

without spe!i$.in" thei mem+e s as shown +elowZ Does this wo 9Z Title1 U Title2> Does the $ollowin" !ode wo 9Z 5h. o wh. notZ Title1#4ame U Title2#4ame !#

C# /how the output and answe the Ruestions $o the $ollowin" p o" am# Hin!lude :stdio#h; *oid main%& I st u!t /on" I !ha 4ameP2,Q> $loat Len"th> L> st u!t /on" Title1 U IDMa *elous 6 a!eD0 2#,@L0 Title2 U IDI /u ende )llD0 3#@L0 Title3> Title3 U Title1> Title1 U Title2> Title2 U Title3> p int$%D1: Title A ]s0 Len"th A ]#2$EnD0 Title1#4ame0 Title1#Len"th&> p int$%D2: Title A ]s0 Len"th A ]#2$EnD0 Title2#4ame0 Title2#Len"th&> L a# 5hen initiali7in" a# 5e need to p o*ide the *alue in o de 0 simila to the de!la ation# +# 4o we !anNt# !# Th ee# That a e Title10 Title2 and Title3# d# The o i"inal *alue o$ Title1 was o*e w itten +. Title2 and the o i"inal *alue o$ Title2 was o*e w itten +. Title3 whi!h was !opied $ om Title1#

st u!tu es0 do .ou ha*e to p o*ide the *alue o$ the $i st mem+e $i st o !an it +e pla!ed se!ondZ +# Can .ou lea*e out the *alue o$ one o$ the mem+e s as shown in the $ollowin" !odeZ Does this wo 9Z st u!t /on" Title1 U I 0 2#,@L0 Title2 U IDI /u ende )llD0 L0 Title3> !# Bow man. *a ia+les o$ t.pe st u!t /on" we e ! eatedZ d# 5hat was done to the o i"inal *alues o$ Title1 and Title2Z ,# /how the output and answe the Ruestions $o the $ollowin" p o" am# Hin!lude :stdio#h; Hin!lude :st in"#h; // sta t o$ st u!tu e de$inition st u!t /on" I !ha 4ameP2,Q> $loat Len"th> L> // end o$ st u!tu e de$inition // $un!tion p otot.pe0 e!ei*es and etu ns st u!tu e data t.pe st u!t /on" _e oOut%st u!t /on"&> *oid main%& I st u!t /on" Title1 U ID5hite oomD0 2#,@L0 Title2> Title2 U _e oOut%Title1&> p int$%D1: ]s0 ]#2$EnD0 Title1#4ame0 Title1#Len"th&> p int$%D2: ]s0 ]#2$EnD0 Title2#4ame0 Title2#Len"th&> a# The p o" am wonNt wo 9 +e!ause the st u!tu e was used in the $un!tion p otot.pe# 5e need to de!la e it +e$o e usin" it# +# Title1 +e!omes x in _e oOut%&# !# 4o# d# 4o# The $un!tion !annot !han"e its !ontents# In the $un!tion we t . to assi"n an empt. st in" to x#4ame and @ to the x#Len"th# Bowe*e 0 when we etu n to main%& the o i"inal *alue still inta!t# e# 1es $un!tion ma9es !op. o$ st u!tu e li9e a s!ala # $# 4o0 it is li9e a s!ala # "# st u!t /on" t.pe# h# . *a ia+le o$ t.pe st u!t /on"# i# Title2 *a ia+le o$ t.pe st u!t /on"# 8# 1es0 those *alues e!ei*ed in main%& and assi"ned to Title2 o$ t.pe st u!t /on"#

L // +e"innin" o$ $un!tion de$inition st u!t /on" _e oOut%st u!t /on" x& I st u!t /on" . U IDBa*e Me !. On MeD0 3#2@FL> st !p.^s%x#4ame0 2,0 D D&> x#Len"th U @> etu n .> L // end o$ $un!tion de$inition a# The st u!tu e is not de$ined inside an. $un!tion# I$ it we e de$ined inside the main%& $un!tion0 as was done in the p e*ious exe !ises0 will this p o" am wo 9Z 5h. o wh. notZ T . it# +# Let us $i st !on!ent ate on how $un!tions e!ei*e a "uments that a e st u!tu es# )s shown in the p o" am0 the de$inition o$ the st u!tu e is "lo+al0 that is0 it is a*aila+le to all $un!tions# Title1 in main%& +e!omes what *a ia+le in _e oOut%&Z !# _e oOut%& e ased the !ontents o$ what was p o*ided th ou"h the *a ia+le Title1# 5e e the !ontents o$ Title1 also e ased when !ont ol went +a!9 to main%&Z d# 5hen passin" a st u!tu ed *a ia+le to a $un!tion0 !an that $un!tion !han"e its !ontentsZ e# Do $un!tions ma9e !opies o$ st u!tu es li9e the. ma9e !opies o$ s!ala sZ

$# Do $un!tions e!ei*e onl. add esses o$ st u!tu es0 as the. do o$ a a.sZ "# Let us now !onside how $un!tions etu n st u!tu es# 5hat is the data t.pe that _e oOut%& etu nsZ h# 5hat *a ia+le is etu ned +. _e oOut%&Z 5hat is its data t.peZ 5hat a e its *aluesZ i# 5hi!h *a ia+les in main%& a!!epts the etu ned st u!tu e $ om _e oOut%&Z 8# 5e e the *alues etu ned +. _e oOut%& e!ei*ed in main%&Z I$ so0 then into whi!h *a ia+leZ W# Bow a+out an a a. o$ st u!tu e# /how the output and answe the Ruestions $o the $ollowin" p o" am# Hin!lude :stdio#h; Hin!lude :st in"#h; st u!t /on" I !ha 4ameP2,Q> $loat Len"th> L> *oid main%& I st u!t /on" TitleP3Q U IIDLone G ai ieD0 2#,@FL0 IDMe . Ch istmasD0 3#3,FLL> int i> puts%DEnte a new son":D&> "ets^s%TitleP2Q#4ame0 2,&> puts%DEnte its time:D&> AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAA

s!an$^s%D]$D0 OTitleP2Q#Len"th0 C&> $o %i U @> i :U 2> ++i& p int$%D]d: ]s0 ]#2$EnD0 i + 10 TitlePiQ#4ame0 TitlePiQ#Len"th&> L a# ?emem+e that indexin" sta ts at @ and ente the initiali7ed *alues o$ the a a. in the dia" am# +# /how the *alues in the $ollowin" dia" am that .ou p o*ided in the a a. o$ st u!tu es#

a# ## +# ## !# Title0 with th ee slots# d# /on"# 4ame and Len"th# e# DonNt +e !on$used# The index is $o the /on" st u!tu e not $o the st u!tu esN elements# The OTitle#Len"thP2Q is an a a. $o the st u!tu eNs element# /o0 the e a e a a. o$ st u!tu es and a a. o$ a a.sN elements# 'oth a e *alid and must +e di$$e entiated !lea l.# $# ) a. name0 index and then mem+e name# "# ' a!9ets# h# ) pe iod#

!# 5hat is the name o$ the a a.Z Bow man. slots does it ha*eZ d# 5hat is the name o$ the st u!tu eZ 5hat a e the names o$ its mem+e sZ e# 5h. is the index p o*ided next to the a a. name and not the mem+e name0 in all the instan!es o$ this exe !iseZ 5h. the $ollowin" isn<t !o e!t: OTitle#Len"thP2QZ $# 5hen a!!essin" an. item in this a a. o$ st u!tu es0 what must +e spe!i$ied $i st0 se!ond and lastZ Choose .ou

answe s $ om: mem+e name0 a a. name0 index# "# )n a a. slot is spe!i$ied +. usin" + a!9ets o a pe iodZ h# ) st u!tu e mem+e is spe!i$ied +. usin" + a!9ets o a pe iodZ X# 4ext0 let us ha*e an a a. o$ names within a st u!tu e# Ente [/atis$ied Mind\0 ['ill.\0 [Sill.\ and [/ill.\ $o the sample input data# /how the output and answe the Ruestions# Hin!lude :stdio#h; st u!t /on" I !ha 4ameP2,Q> !ha /in"e P3QP2,Q> $loat Len"th> L> *oid main%*oid& I int i> st u!t /on" Title1 U ID/ee9 and dest o.D0 D?un $o .ou li$eD0 D'eauti$ul SasmineD0 DMa9e m. da.D0 2#,@L0 Title2> puts%DEnte a new son":D&> "ets^s%Title2#4ame0 2,&> puts%DEnte its 3 sin"e sD&> s!an$^s%D]sD0 OTitle2#/in"e P@Q0 2,&> s!an$^s%D]sD0 OTitle2#/in"e P1Q0 2,&> s!an$^s%D]sD0 OTitle2#/in"e P2Q0 2,&> p int$%D]sEt]sEnD0 Title1#4ame0 Title2#4ame&> a# ) usual0 it is +ased on the a a.Ns index# Index @ will sto e st in" 1 as in Title2#/in"e P@Q0 index 1 will sto e st in" 2 as in Title2#/in"e P1Q and index 2 will sto e st in" 3 as in Title2#/in"e P2Q#

p int$%DEnD&> $o %i U @> i :U 2> ++i& p int$%D]s0 ]sEnD0 Title1#/in"e PiQ0 Title2#/in"e PiQ&> L a# /o $a ou st u!tu e has had one mem+e that was an a a.# Bowe*e 0 we t eated it as a sin"le unit o a st in"# Be e0 we ha*e a 3Aslot a a. o$ st in"s that hold the names o$ sin"e s# 5hen initiali7in"0 how do we 9now whi!h st in" "oes into whi!h slot o$ the st u!tu eZ +# /how the !ontents o$ all lo!ations in the $ollowin" Fi"u e#

!#

d# e# $# "# h#

!# 5hen eadin" in the name mem+e o$ Title20 wh. is no a a. index "i*enZ

i#

+# ### The name st in" is !onside ed as one element# The a a. has +een used to sto e the indi*idual !ha a!te and the index o$ the a a. is one dimensional# In this !ase we ha*e th ee st in"s to +e ead and sto ed into th ee di$$e ent slots and the a a.s a e two dimensional# 4ot spe!i$ied +e!ause the son" names ha*e +een !onside ed one element and the index is one dimensional# The a a. indexes a e spe!i$ied +e!ause e*e . sin"e name has +een !onside ed a di$$e ent st in"# 'ased on the dimensional o$ the index# I$ it is two dimensional0 then we need to spe!i$. an index# In exe !ise HW0 the st u!tu e mem+e and the st u!tu e *a ia+le spe!i$ied with an index and this is a st u!tu e that !ontains an a a. element and then de!la ed as an a a. *a ia+le# The use o$ the sRua e + a!9ets %P Q&# 5hi!h one o +oth that ha*e the + a!9ets

d# 5hen eadin" in the sin"e s $o Title20 wh. is an index spe!i$iedZ e# 5hen p intin" the son" names0 a e a a. indexes spe!i$iedZ 5h. o wh. notZ $# 5hen p intin" out the sin"e s0 a e a a. indexes spe!i$iedZ 5h. and wh. notZ "# '. loo9in" at the st u!tu e de$inition0 how !an .ou tell whi!h mem+e needs an index spe!i$iedZ h# In exe !ise HW0 was the *a ia+le name o the mem+e name spe!i$ied with an indexZ "et an index# i# '. loo9in" at the st u!tu e 8# In this exe !ise the st u!tu e mem+e and/o *a ia+le de$initions0 how names spe!i$ied with an index as !ha !an .ou tell i$ the *a ia+le name 4ameP2,Q> and !ha /in"e P3QP2,Q> o the st u!tu e mem+e name 9# 5e need to de!la e the st u!tu e mem+e "ets an indexZ and the st u!tu e *a ia+les as an a a. 8# In this exe !ise0 was the t.pe as shown +elow# *a ia+le name o the mem+e st u!t /on" name spe!i$ied with an indexZ I Bow !an .ou tell whi!h one !ha 4ameP2,Q> should +eZ !ha /in"e P3QP2,Q> 9# /how how .ou would ha*e to $loat Len"th> !han"e the de$inition o$ the L> st u!tu e and/o the *a ia+le so ### that +oth indexes would ha*e to st u!t /on" Title3P3Q> +e "i*en when a!!essin" a ### sin"e # Title3P@Q#/in"e P@Q U I DMa. da.DL> &ore +tructure 3uestions Fo the $ollowin" Ruestions0 use the de$initions o$ the "i*en st u!tu e# st u!t Date I int ..0 mm0 dd> L> st u!t Emp I

!ha Emp4ameP2,Q> $loat /ala .> st u!t Date hi ed> L> st u!t Dep I st u!t Emp mana"e > st u!t Emp wo 9e P2,Q> $loat G o$its> L>

1# De$ine a st u!t Date *a ia+le !alled Date1 and initiali7e it to Fe+ ua . 2,0 19,X0 in the !o e!t $o mat#

st u!t Date I int ..0 mm0 dd> L> *oid main%*oid& I st u!t Date Date1> Date1#dd U 2,> Date1#mm U 2> Date1#.. U 19,X> p int$%DThe date U ]d0 ]d0 ]dEnD0 Date1#mm0 Date1#dd0 Date1#..&> L

2# De$ine a st u!t Emp *a ia+le !alled Ge son1 and initiali7e it to [?o"e \0 with a sala . o$ `,@0@@@0 who was hi ed on Ma !h 1@0 2@@1#

Hin!lude :stdio#h; st u!t Date I int ..0 mm0 dd> L> st u!t Emp I !ha Emp4ameP2,Q> $loat /ala .> st u!t Date hi ed> L>

*oid main%*oid& I st u!t Emp Ge son1 U ID?o"e DL> Ge Ge Ge Ge son1#/ala . U ,@@@@> son1#hi ed#mm U 3> son1#hi ed#dd U 1@> son1#hi ed#.. U 2@@1>

p int$%DBi ed Date U ]d0 ]d0 ]dEnD0 Ge son1#hi ed#mm0 Ge son1#hi ed#dd0 Ge son1#hi ed#..&> p int$%DEmplo.ee 4ame U ]sEnD0 Ge son1#Emp4ame&> p int$%D/ala . U `]#2$EnD0 Ge son1#/ala .&> L

3# De$ine a st u!t Dep *a ia+le !alled To.s whose mana"e is [?o"e \0 $ om Ruestion 2 a+o*e and the p o$its a e `Y@0@@@# This depa tment has onl. two emplo.ees as shown +elow: [Moha*e\ with a sala . o$ 1@0@@@ and the date o$ hi e +ein" )p il 2@0 2@@2 [Bunte \ with a sala . o$ Y0@@@ and the date o$ hi e +ein" Sune 120 2@@@

Hin!lude :stdio#h; st u!t Date I int ..0 mm0 dd> L> st u!t Emp I !ha Emp4ameP2,Q> $loat /ala .> st u!t Date hi ed> L> st u!t Dep I st u!t Emp mana"e > st u!t Emp wo 9e P2,Q> $loat G o$its> L> *oid main%*oid& I // note the o de o$ the a an"ement

// IEmp4ame0/ala .0I..0mm0ddLL0 IIEmp4ameP@Q0 /ala .0I..0mm0ddLL0 //IEmp4ameP1Q0/ala .0I..0mm0ddLL0###0 IEmp4ameP2CQ0/ala .0I..0mm0ddLLL0 //IG o$itsLL st u!t Dep To.s U IID?o"e DL0 IIDMoha*eDL0 IDBunte DLLL> To.s#G o$its U Y@@@@> To.s#wo 9e P@Q#hi ed#mm U C> To.s#wo 9e P@Q#hi ed#dd U 2@> To.s#wo 9e P@Q#hi ed#.. U 2@@2> To.s#wo 9e P@Q#/ala . U 1@@@@> To.s#wo To.s#wo To.s#wo To.s#wo 9e 9e 9e 9e P1Q#hi ed#mm U W> P1Q#hi ed#dd U 12> P1Q#hi ed#.. U 2@@@> P1Q#/ala . U Y@@@>

p int$%D]s is a mana"e EnD0 To.s#mana"e #Emp4ame&> p int$%DCompan. p o$it is ]#2$EnD0 To.s#G o$its&> p int$%DBi ed Date $o ]s is ]d0 ]d0 ]dEnD0 To.s#wo 9e P@Q#Emp4ame0 To.s#wo 9e P@Q#hi ed#mm U C0 To.s#wo 9e P@Q#hi ed#dd U 2@0 To.s#wo 9e P@Q#hi ed#.. U 2@@2&> p int$%D/ala . U `]#2$EnD0 To.s#wo 9e P@Q#/ala .&> p int$%DBi ed Date $o ]s is ]d0 ]d0 ]dEnD0 To.s#wo 9e P1Q#Emp4ame0 To.s#wo 9e P1Q#hi ed#mm U W0 To.s#wo 9e P1Q#hi ed#dd U 120 To.s#wo 9e P1Q#hi ed#.. U 2@@@&> p int$%D/ala . U `]#2$EnD0 To.s#wo 9e P1Q#/ala .&> L

C# Usin" one p int$%&0 p int the !ontent o$ Date1#

/ee H1

/ee H2 ,# Usin" two p int$%&<s0 p int the !ontents o$ Ge son1# W# 5 ite a $un!tion !alled Hin!lude :stdio#h; G intEmp%& that will e!ei*e a st u!tu e o$ t.pe st u!t Emp and *oid G intEmp%st u!t Emp&> p int its Emp4ame0 /ala . and Date hi ed# Callin" this $un!tion st u!t Date th ee times and usin" an ext a I p int$%&0 p int the !ontents o$ int ..0 mm0 dd> To.s# 1ou ma. want to d aw a L> dia" am to help .ou see the !omponents o$ To.s# st u!t Emp I !ha Emp4ameP2,Q> $loat /ala .> st u!t Date hi ed> L> st u!t Dep I st u!t Emp mana"e > st u!t Emp wo 9e P2,Q> $loat G o$its> L> *oid main%*oid& I // note the o de o$ the a an"ement // IEmp4ame0/ala .0I..0mm0ddLL // Let ma9e it somethin" li9e this $o easiness // st u!t Emp 4ames@ U ID?o"e DL> // st u!t Emp 4ames1 U IDMoha*eD0 1@@@@0 IC0 2@0 2@@2LL> // st u!t Emp 4ames2 U IDBunte D0 Y@@@0 IW01202@@@LL> // Then !on*e t it to an a a. st u!t Emp 4amesP3Q U IID?o"e DL0 IDMoha*eD0 1@@@@0 I2@@20 C0 2@LL0 IDBunte D0 Y@@@0 I2@@@0W012LLL> st u!t Dep To.s U IID?o"e DL0 IIDMoha*eDL0 IDBunte DLLL> G intEmp%4amesP@Q&> p int$%DEnD&>

G intEmp%4amesP1Q&> p int$%DEnD&> G intEmp%4amesP2Q&> p int$%DEnD&> To.s#G o$its U Y@@@@> To.s#wo 9e P@Q#hi ed#mm U C> To.s#wo 9e P@Q#hi ed#dd U 2@> To.s#wo 9e P@Q#hi ed#.. U 2@@2> To.s#wo 9e P@Q#/ala . U 1@@@@> To.s#wo To.s#wo To.s#wo To.s#wo 9e 9e 9e 9e P1Q#hi ed#mm U W> P1Q#hi ed#dd U 12> P1Q#hi ed#.. U 2@@@> P1Q#/ala . U Y@@@>

p int$%D]s is a mana"e EnD0 To.s#mana"e #Emp4ame&> p int$%DCompan. p o$it is ]#2$EnD0 To.s#G o$its&> p int$%DBi ed Date $o ]s is ]d0 ]d0 ]dEnD0 To.s#wo 9e P@Q#Emp4ame0 To.s#wo 9e P@Q#hi ed#mm U C0 To.s#wo 9e P@Q#hi ed#dd U 2@0 To.s#wo 9e P@Q#hi ed#.. U 2@@2&> p int$%D/ala . U `]#2$EnD0 To.s#wo 9e P@Q#/ala .&> p int$%DBi ed Date $o ]s is ]d0 ]d0 ]dEnD0 To.s#wo 9e P1Q#Emp4ame0 To.s#wo 9e P1Q#hi ed#mm U W0 To.s#wo 9e P1Q#hi ed#dd U 120 To.s#wo 9e P1Q#hi ed#.. U 2@@@&> p int$%D/ala . U `]#2$EnD0 To.s#wo 9e P1Q#/ala .&> L *oid G intEmp%st u!t Emp 4ames& I p int$%DEmplo.ee name is ]sEnD0 4ames#Emp4ame&> p int$%DDate Bi ed is ]d0 ]d0 ]dEnD0 4ames#hi ed#mm0 4ames#hi ed#dd0 4ames#hi ed#..&> p int$%D/ala . is `]#2$EnD0 4ames#/ala .&> L

Potrebbero piacerti anche