Tải bản đầy đủ - 0 (trang)
Chapter 4. Character Strings and Formatted Input/Output

Chapter 4. Character Strings and Formatted Input/Output

Tải bản đầy đủ - 0trang

defineandusesymbolicconstants.



IntroductoryProgram

Bynow,youprobablyexpectasampleprogramatthe

beginningofeachchapter,soListing4.1isaprogramthat

engagesinadialogwiththeuser.Toaddalittlevariety,the

codeusesthenewC99commentstyle.



Listing4.1.Thetalkback.cProgram



//talkback.c--nosy,informativeprogram

#include

#include//forstrlen()prototype

#defineDENSITY62.4//humandensityinlbspercuft

intmain()

{

floatweight,volume;

intsize,letters;

charname[40];//nameisanarrayof40chars



printf("Hi!What'syourfirstname?\n");

scanf("%s",name);



printf("%s,what'syourweightinpounds?\n",name);

scanf("%f",&weight);

size=sizeofname;

letters=strlen(name);

volume=weight/DENSITY;

printf("Well,%s,yourvolumeis%2.2fcubicfeet.\n",

name,volume);

printf("Also,yourfirstnamehas%dletters,\n",

letters);

printf("andwehave%dbytestostoreitin.\n",size);



return0;

}



Runningtalkback.cproducesresultssuchasthefollowing:



Hi!What'syourfirstname?

Sharla

Sharla,what'syourweightinpounds?

139

Well,Sharla,yourvolumeis2.23cubicfeet.

Also,yourfirstnamehas6letters,

andwehave40bytestostoreitin.



Herearethemainnewfeaturesofthisprogram:

Itusesanarraytoholdacharacterstring.Here,someone's

nameisreadintothearray,which,inthiscase,isaseries

of40consecutivebytesinmemory,eachabletoholda

singlecharactervalue.

Itusesthe%sconversionspecificationtohandletheinput

andoutputofthestring.Notethatname,unlikeweight,

doesnotusethe&prefixwhenusedwithscanf().(As

you'llseelater,both&weightandnameareaddresses.)

ItusestheCpreprocessortodefinethesymbolicconstant

DENSITYtorepresentthevalue62.4.

ItusestheCfunctionstrlen()tofindthelengthofa

string.



TheCapproachmightseemalittlecomplexcomparedwiththe

input/outputof,say,BASIC.However,thiscomplexitybuysa

finercontrolofI/Oandgreaterprogramefficiency,andit's

surprisinglyeasyonceyougetusedtoit.

Let'sinvestigatethesenewideas.



CharacterStrings:AnIntroduction

Acharacterstringisaseriesofoneormorecharacters.Hereis

anexampleofastring:



"Zingwentthestringsofmyheart!"



Thedoublequotationmarksarenotpartofthestring.They

informthecompilerthattheyencloseastring,justassingle

quotationmarksidentifyacharacter.



TypecharArraysandtheNullCharacter

Chasnospecialvariabletypeforstrings.Instead,stringsare

storedinanarrayoftypechar.Charactersinastringare

storedinadjacentmemorycells,onecharacterpercell,andan

arrayconsistsofadjacentmemorylocations,soplacingastring

inanarrayisquitenatural(seeFigure4.1).



Figure4.1.Astringinanarray.



NotethatFigure4.1showsthecharacter\0inthelastarray

position.Thisisthenullcharacter,andCusesittomarkthe

endofastring.Thenullcharacterisnotthedigitzero;itisthe

nonprintingcharacterwhoseASCIIcodevalue(orequivalent)is

0.StringsinCarealwaysstoredwiththisterminatingnull

character.Thepresenceofthenullcharactermeansthatthe

arraymusthaveatleastonemorecellthanthenumberof

characterstobestored.

Nowjustwhatisanarray?Youcanthinkofanarrayasseveral

memorycellsinarow.Ifyouprefermoreformallanguage,an

arrayisanorderedsequenceofdataelementsofonetype.This

examplecreatesanarrayof40memorycells,orelements,

eachofwhichcanstoreonechar-typevaluebyusingthis

declaration:



charname[40];



Thebracketsafternameidentifyitasanarray.The40withinthe

bracketsindicatesthenumberofelementsinthearray.The

charidentifiesthetypeofeachelement(seeFigure4.2).



Figure4.2.Declaringavariableversusdeclaring

anarray.



Usingacharacterstringisbeginningtosoundcomplicated!You

havetocreateanarray,placethecharactersofastringintoan

array,onebyone,andremembertoadd\0attheend.

Fortunately,thecomputercantakecareofmostofthedetails

itself.



UsingStrings

TrytheprograminListing4.2toseehoweasyitreallyistouse

strings.



Listing4.2.Thepraise1.cProgram



/*praise1.c--usesanassortmentofstrings*/



#include

#definePRAISE"Whatasupermarvelousname!"

intmain(void)

{

charname[40];



printf("What'syourname?\n");

scanf("%s",name);

printf("Hello,%s.%s\n",name,PRAISE);



return0;

}



The%stellsprintf()toprintastring.The%sappearstwice

becausetheprogramprintstwostrings:theonestoredinthe

namearrayandtheonerepresentedbyPRAISE.Running

praise1.cshouldproduceanoutputsimilartothis:



What'syourname?

HilaryBubbles

Hello,Hilary.Whatasupermarvelousname!



Youdonothavetoputthenullcharacterintothenamearray

yourself.Thattaskisdoneforyoubyscanf()whenitreadsthe

input.Nordoyouincludeanullcharacterinthecharacterstring

constantPRAISE.We'llexplainthe#definestatementsoon;for

now,simplynotethatthedoublequotationmarksthatenclose

thetextfollowingPRAISEidentifythetextasastring.The

compilertakescareofputtinginthenullcharacter.

Note(andthisisimportant)thatscanf()justreadsHilary

Bubble'sfirstname.Afterscanf()startstoreadinput,itstops

readingatthefirstwhitespace(blank,tab,ornewline)it

encounters.Therefore,itstopsscanningfornamewhenit

reachestheblankbetweenHilaryandBubbles.Ingeneral,

scanf()isusedwith%storeadonlyasingleword,notawhole

phrase,asastring.Chasotherinput-readingfunctions,suchas

gets(),forhandlinggeneralstrings.Laterchapterswillexplore

stringfunctionsmorefully.



StringsVersusCharacters

Thestringconstant"x"isnotthesameasthecharacter

constant'x'.Onedifferenceisthat'x'isabasictype(char),

but"x"isaderivedtype,anarrayofchar.Aseconddifference

isthat"x"reallyconsistsoftwocharacters,'x'and'\0',the

nullcharacter(seeFigure4.3).



Figure4.3.Thecharacter'x'andthestring"x".



Thestrlen()Function

Thepreviouschapterunleashedthesizeofoperator,which

givesthesizeofthingsinbytes.Thestrlen()functiongives

thelengthofastringincharacters.Becauseittakesonebyteto

holdonecharacter,youmightsupposethatbothwouldgivethe

sameresultwhenappliedtoastring,buttheydon't.Addafew

linestotheexample,asshowninListing4.3,andseewhy.



Listing4.3.Thepraise2.cProgram



/*praise2.c*/

#include

#include/*providesstrlen()prototype*/

#definePRAISE"Whatasupermarvelousname!"

intmain(void)

{



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Character Strings and Formatted Input/Output

Tải bản đầy đủ ngay(0 tr)

×