acanf and printf .which support formatted reading and writing, an two of th-e most frequently DBOd functions in 'C. " "'.1 this chapter shows, both are powerful but tricky to use properly. Section 3.1 describes printf and Section 3~2 covers acanf , Neither section gives complete details which will have to 'wait until Chap-

ter 22'1'

The p,rintf fun crionis designed, to display 'the contents uf a string .. , known as the fom"tzlltri'~Il,' with values pas ibly inserted at specified points in the string. When it's celled, p.r Lnt.f must be supplied witb the format string, followed hey any values that are to be inserted intothe string during printing:

..... ' • t, f !i!" ,,',.' . " '~ , .', I ,i" . )1 .'

p, .... a.n '\, sn lng, exps I" ,exp1l j •• ~' "

The values displayed can be constants variables or more complicated expressions. There is no limit 0'0 the number elf values that lean be printed b1y ,8 si11811!e call of

'. 'f

p,,,, r· In't '

~", - ,I, iii

The format string may contai n both O{{11DBil characters end eonversio« spieciif!!

fic,atitJlJl, which begin w ith 'tile % character, A convers ion specification i· ,3 plac ~ _, holder representing a value Ito be fined in during printing, The- imormati,lon that follows the % character specifies bow the value is convened from its, internal form (binary) to printed form (character )-, that's where th ~ term "conversion specification" comes from. For example, the conversion t pecifieation \'d scecifies thl,t pri,ntf is (0 convert an, Lnt; 'V,IJUIC Irom blnaty "to 13 string ofdecimal di,git' '~I while %f does the same for ,3; fl.oat; value,


Ordin. , ch rac--r ~ in I' 'rm .L strirn aI"( printed .' · tl,Y '_ ~h, .• · ap_'-' ar in th

stri 11 ~:~ 1[;10'"' 1 rsicn ~ p" 1 - • : icarion - I are replace b th e alues Ito be printed. ICon ~ ,id. ,'"

hi follo ing example:


:Ln'l,.. 1. ~ J;

float xv"

~ 'L'

i - 10 ~
. 20
J - ..
x .... 43 28,912£'"
_, . _ ,f
Y = 5S.~1 Otf ..
~ , j, x., y) i

The ordinary characters in the ormat string are simply copied to the output line. be . ur con .'., lOon " peel ications I le r olaced bytb aiu I .... [}I the ariable L, j ..

x and y in that order ..

,C_ompilet·,; aren t required Ito che k th,at [11 number of COllver .. ion sp ifications in torma .. ~ ,_,ing m tche the numbr of' ou pu items, The f III wing call '. f pr'intr has more conversion specifications than value . to b printed:

pr'intfwW printthe value of i correctly th .. D print a seeond (rneaningles s) mte'~ ger valu .. ,' . U th 0 I'."W> nversion s pe ci 'catin. hasslmilar oroblems:

1*** WRONG *1£oft-/

In, this 'C" '. e. pri tfprint the. _ alue of i. does 't h _ he, alue I· _ j"

""urthermo,re- eompilers an n' t r'e_ aired to check that a conver ,~on . peci fication i appropri te or til typ fi,l. m being printed [f the programmer uses an incorrect specific rion, (he pro~-_-,am.· ill : irnpl pr duce - " aninglesseutpur, (,ID' ider lh e . 011 owing call of pz f.ntt in which tb. int variable i and lIt- float _' ariabl - x ar . in the wr.n

1** WRONG ** I

Since printf mu bev tb, formal string, it will-utifuH, display a floa~ value, followed by an int value .. Unf rnU1I't J, b th will be' meaningless.

CODV_' sion _ pecffleatio __ ~

: I, nven L n specifiea ic 1 ive lh pr rrarnmei a gres de J I _ I. ontr I over tIl

appearan ~. of '1u~pUL On - he other ]t811d he· .. nne I~' mpltc ated and har ,,' read, In fact, describing 'COlliver- in spe iii lJtim ill . ornplete detail is too arduous a

r.InIl IIIiiIiI

task rc tac_ .th i : e , ~, , i - lbl' b ,k~ In: 'l _ ad, W -' II jI U" t t ri ' ~ I

thew more ] mpertant capa ill I es,

In ChapterZ we aw that ,3, C n I~ _ sion ,p ci iI:~j[J.tion can inc I ude formatting information. In particular.we used %" If to display a f Loat; - alu 'with on di i aft ,-' tlu decimal p int, viore enerallv . _ onversion sp cification can h_c te he form %/U !lfJIX or %-"""l1t ;~pX where In and p ,- r ' integer con" rants dud X i a letter, Both 111 and p are option ]" i r P is omitted, the pe iod that- eparates ,,1.1 and p is also dl"O;PP 'd. In the eonversion specificaticna i.o . 2f m L, lO,~.p i- 2 .. , and X ls f', In the specification % 1 0 f, IU 'i -' 1 nand p (along with th period) i -, Ini, sing, but In "he

pecification %: Ii 2£ pi" 2 and In ismi ing,

'The "",il,im',flIII,jie'rid 'width" m, r~p ifie th minimum nurnoer f haraet rs to print, tbr -, value 'to be printed require: fewer than In characters the valu i" rightjustified within the field. (In other words extra pacer prec ~ de the ValUI, .J For example the peci ication %4,d' ould display tb ' number 123 as 123. In thi ' chapter I'D u e • to represent thl' 'pace character.) If IDle valu to b printed require' mor ~- than '11' characren ;~, the field width automaticalf e - pands [0 the neeessary .. ize. Thus.vthe ~ pecification %4,d would di splay the number 123 5 a 12345-00' digits are Lost PU'ttU1g a minus sign in front of m cause ' left justi _ rcation; the . P c ification % - 4, d ' ould displ 123 _ 123, .'.

Th meaning 0 the pFlJc,isioll, p, in l W' easil- de crib I d mce it dr p md on th choice of X the CO"p1fl,rsio,,, specifie ., X indican - whi b conve sion should be applied to the value before it ' print d. The mostcommon conver - ion specifiers for' numb rs at :

I. d - Di : 'plays ,an integer in '.- im I' b se ] 10) form, p indi ,-,ate· the minimu number of digit to display (extra eros, are added t10 the b ginning ,of the Dumb ar if necessary): if p is omitted. it is assumed Ito have th alu - 1" (In other w- rd- "I ~d is the same at' % ,_ Ld, I

• e - Display: a floating .... poi t umber in exp nenti.al form t (scientifi notation " p indican how many digit should appear after the c"~ICimaI p ,·nt ( , default i- 6)~ If pi-, 0 the decimal point is net displayed,

• f - Di' play -, -- fl . in . -poinr number in "fixed decimal" for-mat _ ithout an e tponent, P has the .. arne meaning a or th e soecifier,

• 9 - Displays a floa ing-point number in ithe- exponential format or fixed decimal format, d pending on the number's size, p indicates [be maximum numb r of signific n dlgin (n,t digits, after the decimal point) :0 be display . ,- i Unlike the f conven ion the 9 conver II m won't sh I" '_ railins zeros, Furthermore if tI]I~'_ alu tn b printed -,,' DO digit after' he de cimal point 9 d e~ n' t dis play the de -- imalpoint,

The 9 specifier is - sp cially U-, ful or displaying rnrmr ers wh : e size can"[ b ".

tie ictd hn th '_ "r,'~ am is written or ilia - tend to vary wid ,j . in size .. u ,e~ -, '0 print a moders t ly large or In d- rat I)' .. all - Llrn - _ . th_ g._ pecifier tlL e~

fixed decimal _ ormat, But when 0." d to print I~ry large ,r '_,' small -umb'- r, the g' specifn r switehes [I exponential format ."01 that the number will require f 'wr

s(lacrlmfS:ftU n~~:ers.7.t There ar 'many ther spe ifien beside %d~ 'te~ %f~ and %g I'U gradually

specAis'rs for HtlBhi .. 7.2 introdu '" -.' man .,f J ern in . ub iequ _ nt . hapter ' .. F I, the f III li· t and for com 1. _ te 5lJBctner;s fo~ c.hawoobrs .7.3 --phmOlio'n ,of the other cap'-biliti,e, . of conversion pecifieations cons ult Section

speoifiers feD I Sfri'fngs )It; 13.3 .= _ ~3~,

The follo ·in- program illustrates tbl.~ use of p~in tf . - rint ill' egers and 11031- ing-p it1' num aer in - _ -i 1L1~, -oIm,at,,,

fpr/,n,tt~c 1'* Pr-ints int and f loa: values in var-Lous fo'rmats .;

int main l(void11


i ..-'0;

x == 83"91 ~,llf;

;; t . 1n'. 1.;

f Loat; X' I'

':_ .. ' II'

printf(1I %d~%5Id '-5d~%,5,~3dll\nlll, d , Ii ii' i} f ,printf (II %:1'0. 3 f 1-%'1.0 .. 3e I %:-] a'g I \n ", x , X jI x);,

retllrn a ,i'


. rall

It" , ...

TI' 1'_b,ar_!_t1er- in the pr'int£ rormm ,trin . am tb lie merely t; h lp sb how much space each numb _ r occupie ~ when pri nted; un I ik ~' % 1 r \, 'the' ~ char eter ha no special' ignifi .ance r I plrintf~, I hie. utput f thi oro -lI11] I:':

401 4D~'O I 0401 a3g.21D~ a.392e+02Ia3g·21

Let . take 1£1 closer look at the c . nversicn specifications used _in this program:

• 1'.d ~ Display . i in Idle· Imal .. rm, using a minimum amount f ~ P -,:' "'

• t Sid - Display i in decimal form us ill a minimum of . rve _ bara_ te - .

Since i require ' only t . ;" chars . t _" hr ,e I 'P' . e', ; . cr dd ·dJO

• %._ Sd ~ Displays i in decimal form~, using a minimum of five character ·

.ince th - alue of ide 11 't re uir II bar .' ter th sp ees are I. dded after-

ward (that is, i is left-justified in n,eJd 0, 'I· ngth five) .

• %5,~ 311d - Display' i in d irnaJ fOlIO usina a minimum _fi" _ cheracters

o I rall land a minimum 0_ thre 'digi .C, inc i L only two di it Ion ani . tria zero wa added to guarantee three digit. ~ -:b -' resul ing numb r is only ,'. lee character long ~O 'l"\"11 pace . ere ' Idded~ fOI a total 0_- five characters Ii', right ~j ustified),

'" ith three digit· after the decimal point SiLD'I:C x requires only 'even eharaeters (three before the d_ 'C'il11S1 point" three after be cimal point, and one for the decimal point itself), three spaces precede x.

• '~1 0 .. :3 e - Di P laysx 111 ex ponential _"' rrn, using 10 character. I. verall , with three digit after the d._ cim .. al poult. x require nine characters altegetner . Including the e ponentj.. - 0- 'o'ne space preeer es x.

• '%~ 1 Og ~ Displays x in either fixed decimal form or exponeadal form" using In eharacters overall. 111'11 this case, printf chose to di -play x ; 1: fixed deeimal, orm, The presence of r}l -' minus slgn forcc lefrjustlflcarion.ao x is followed by four spaces,

The \n code that W"e oft· II use in format strings is. called an "Bcap" slfJrp,e~,"c,e,. Escape sequences enabl e string .. to contain characters that would otherwise cause P' .oblem fo:r the compiler, inc' uding ntO'l] )rinting control) charar ters ,ID _ characten thm hay ~" ,I special meaning tel the compiler I( nch as U l. 'We"U prolvi a -om,-

e:SGaj~na seq lJ,e nee s }l-7.3 plete Iist of escape sequences later: for now, here's a sample:

A]erl (ben) \a

Backspace \b

New line \n

Horizontal tab \ t

When thle,Y appear in pr Lnt; f l)arma: - strings these escape .• equ _IlIIC'_·· Ii ~~pre ent action. 'ID perform upOtn printing, Prinrinn \ a ans es an audible beep on most machine: ,. Printing \b'lnove·, 'the cursor back one po sition. Printing \-D, advance the leur 'or to the beginning - the next line, Printing \ t m.oy· s ,- e cursor to 'tbe next tab stop,

A '- triag may conn in 811'Y number of escape sequence s. I'. onsider the following pzLnt; f example.jn which 'the format string contains.six B~ c,ap . s qu- nees:


U- ~ t ~n_I-=,


PUrchase Date

Another common escape sec uenee is \ M ,~. which reptie· enn (he 1111 character, Since the ~. character marks the beginning and lend 0 ~ a 'Iring, it can't appear within a string wirbout the u se gf th! es cape equence, eire s an example:

Tl is natement produces the following output:

W, I \ cb ,I t - in ~ trlng; tl _ c mpil r

zap uen e. . II~ print ,~ ~. ingle \ char-

Inci entallyco, 'IU can" t ~!D. l put a wil ussum,e th __ l it s, the _ _ inning of' I acter .. put tw I \ characters in the string:

1* pr~nts one \ character *1

Jus , pzi.nt.f prm,.' ! lltpu in . pecmed tormat, s,'anf re,ai' 1., lB' ut .' 'cardin!

parti ular ormat,' acanf formats ing, like a printf arm t ing, m ,'Y contain both ordinary characten and convert ion' ,P cificasion .... The conversions ,all wed ' ith s,canf OJ" ~, enti U)/' the anle' . U1(i -:' used . ith print f ~

ln man c I. es . a scanf forma strim ill contain pecifica-

Ii ,', ru . as 'j n rh foU,·,· ina e ample:

int L, j; ·float ,x, Y"

. uppose that" he 0 er enter, tbe followin input lin" :,

acanf 'illl"e,- d the lin, - n erung L' ha a ct rs t . th numbers thev '_' -e· nil , nd Olen ")r' n 1. -21 c I: I,. ,'I and -40 '. '.0 0 i, j ~ x and y~, re ,p ctiv I~ '" "Tightl packed" tom] ,t strings lie III %d%d%£~fU are common in acanf C1 1· .. pzLrn.f fcnuatstring ar-e less likely to h~_VI'.' adjac nt conversion sp -IC'ifiea,ti. n '.

acanf, He print! contains ..... , eral tra - . me Un-' a- . Wh, n It in,

acanf the programmer. _U t e heck that b numb r II I -I n· = i n "_ ',"51 II "aLi- as

matche .. the' number 0' i'n~ ut ariable .. and tbal each con rs ion !', P ropriate .or the corre pending van ble=-a with prin'tf, the compil r is r't requl d t "heck f r a po 'ii Je mi match, Ani ther trap in 1 Iv I. the s I ·'mb 1. 'which D: rrnall- pr '-

.. 1-,1 each var able in scanf call, The & LI usuall (but not ~dw,-I_ ~,I re __ uin '. am d it, the pro' rammer responsibilitj l rememb [ to 01 it.

1:\. ill,

Forgetting to pu the' &ymbal in front of a ariable in a, call. of scanf win have unpredicteble=-and posr ib] disa trou c,~ll ult .. A pro,' ,am crash L ~ common outcome, .,1 . cry least II e value that i read ,10m inpu n' , _ tored in th . ' ariabl '~, instead, tb v' ri tble will r _ ~, it Id : alue '" 'hich I is b meaningless if the variahle wasn't Iven an I ~'tiaJ alue), Omitting [he &. i an exrrem L common error-vbe carefull Some compile ,. can 'pot this error and' produce a

. h It •• Ii, (Tb ..'

11l1:llD,g In '. -abc sue - ,as ·rtnal'· rtlln,l_ ,~~, not la pointer: I '. ·tl,. nil panfil ,. ,I "

d· fine in' h pter I) . the &. 'c' ' mbol i u . d I rean a minter l01 ariable, If Olm

1- ' a warning check _:r,~ missing &~.

Caning acanf i a powerful but unfor ivio,_ wa to r ~d d . '_any pr fe - sional C programmers avoid sc.anf", ill I tead reading an data in character form and converting it to numeric form lat. r; We II use acranf quite a bit especi 11y in U;. early chapters of hi, book becans it provide a simple . a to re, d num - -. Be it ;- an '~I howe" J~ that many O:U ogran ,'D t bebav It' iperly if. '~h' u er ent r unexpect d input A 'we - U see later; j t's possi le t hav ,8 program te t

d'eteeJUng errors i;~ acenf .22~8 W hethe r s c: anf successfully read the reque -,t,ed data ( nd 'att, mpt to rt'lC'OVC" if it didn t), Such tests are impraeti at for the PIlO - ,r In -. in tblt- - -they - -Iuld add tn· I many statement I,an I 'Ib cure the noint -f 'b examples,

RIO s'c,anf Wo,rks,

acanf can actually do much more than I'v - in icated 'I ·,at" 11 i. ess entlally a 'pa!Lern~n1a[,chin,g' function that tries :0 mar b U I grc Up", of inpu charai ers with

conver si '.111' pecifieations,

Like rbe printf function, s'can,f is . xmtroile by Lh formal strinr .. -. ren it

alled, acanf begins proces sing ll- e in forrtl at"' n [11 th tring'~1 startin - at the

left, or each- on r Ion specification in "the format string, acanf tries t locate an :i em of the appropriate type in the inpu ta skipping bl n I pace if n .. ce ssary

ac arrf then read the item, t ~ ping when it 11:_ unte -; . b rae till I .

". ibly belong to the' item, If the Item WQ? ret d 'U -_ J' fully" s.eanf continu processing the rest of the format string. lJm]~y item i, nul read" uccessfully, acemf re urns immediately wirbout 10 ·kin al the' - - t of the formarstrim (or the rerru ining input data).

A'~ i search _. for the beg inning 0 a numner s canf i pre', ~ hi:t,-s"Q'" character» (the space, horiaontaland . ertical tab, form-feed, .nd new -line characters) .. Asa re mlt, DUl- biers can b ' put nn a . ingle line or spread out OYer everal line'. CO' .. ider the following cal] , r acanf:

- .- f ( II C!.dc d%f Q.f U & . & • &x.. 1"_ -) •

sean, 11· 11 'tD " .~. , . - J ~ .'~ It O£y r

Suppose that the u . '.r enter, three line·' o input: 1

-20 .3


scenf eees OJ1.e, orninuous tream of charaerer -:

(1 m using .' [0 represent be spac clu --II_t_' an . C I I represent th . ne· -line Wbt -~ act r~.) '. ince it skip over whit .- ace characters is it lk- to the b egmning of leach number, scan_f will b able to read the numbers successfufly, In tb ~ llowing diagram, an e under a charaet r indicate Lb,a~ it was skipped and an r indi ..

(!'3 it was read ft, part. an input item:

•• 10 20 •• ·.30·.·-4.0e30 S 5 rsrrrs,s,s ers B S S rrrrrr

8ca'nf~'p_ ~-'_" at the final new-line char ter with Ul a mal" r adlng it. Thi new-line JU' -e the fin t character re td by the next call of sc,an_f,

What rule d ,'lL scant f llo [0 recognize an integer ora, floating-p int number., ;0 asked r reaa a inie ~ c_ r, acarif firs l e ches for dlgi - I,:' plu

sign or inu 'ign',L then re '_ di its until it reac es r nondigit, "b''Oaskedr-

read a 'fl 'atiing-poinI num ber s canf loo I

an e '~Ol1enl Qprtilon 11. An exp sign .. and nne or more digi' s,

The t'e, 'f . md '" 9 c nv _ rsion '> are i nt rchangeable when used wi h G cs D f:; all

three follo , tb _ sam, rule I: lor recosnizin u a _ " g-poi nt nutn 1':.

- C ': 'n s canf 11211, unters ,a chara -ter ilia c n - 't - -' ~ art ()I_ tl 'CUJ]i.iJl] item- 'rb

E1II character is put ba k" til b read ;g' in uring the sc nning of the n ,~- mpu Item or during the '[]Lxtt call of B,ca.nf., Con ider the follewing (admittedly path Jogical) arran aeme nt of OL1f our number .:

- ',0 - -

,," plus or minus ',ign (oprional}, ollowed 'y

a • ' erie ' of digi t·' , (po sibly containing a decinn P int I,,. ,Do" db',

old pIO re ' th ne input:

I. en' ersion :spef lfi, ati n: %d_ The first nonbl n ill' ut character i, 1:iuc',e i ntegen can begin wlth 1;1 s can I then read th next Cb21Xa(;t~ 'r~ - '" Rccogni - in __ 'that _, , an tapp ar Inside an lntezer scanf I' If 1 int i and pun the ~ ch fl- cter bae ~

• C, ,n-' er ion I peei I I ,.. n:: % d. s c:anf then re ds th I -har~ I' -:2, Ol~, an, I :0

period). Since an b11J 'ger call t contain a decimal porn, acanf tores s- 0 in I j n ,- puts be ~ character bell"

Cc 'n~ ersion lPICi~L '_ at1 11: S:-f~ scanf read, the c aracter '" ,3", and - ~ Sin e

floatinj -point Dumb r I an 'n inn .',. n - e- a d"'!!1' aoarif 'tore'

I .J. Into x and put the » chan cter - la~ __ ~

• Conversion speelf cation: %f" Lastly .. acanf read the characters -. 4, or. 0 e .3 :lrlld'D (new .. Yn '" Since r fl ating-peint numb r eaa II nev -line . :h~ ract r acanf tor ,I =4~Ox ]O~ into Y Mid put the nex -lin ' character back,

In 'this example, scanf was abl ' II march Ie;rve:ry c_"ODV' _ ~'"IO'III .,. pecifieati . n in the format trin with an i ~]~ out i'tem.,"inl, e the Dew-lin character w'· sr It r -= ad" it will

be I, ~: r th n xt call, ,s'canf ~

The . n ept of pattern -n· ching r

, ' 11,' If ,on ain ordin .

a. I cr In

' .. When it en "unt ~'baraL ter in a ,- tf~ - '_

'- ing s,c'lanf' I, llnp,=. - ~ iu- ith 'e. '1 'in ut eharac r, If the w chara rs

m stch, acanf discard the input chi "! eter and ~ .. , cOli ' JI[1, ceasing the tier ... mat . trim . If th eharae er d .'.10 t march scant pu I the offendin'~ char aeter back into Ole inpu -li len aborts 'without further PI-, .'" .0 the format triD. r reading charact r' -. om, the input,

For example suppose that the I orm t strin i;' I ~dl %d HI ,. If the input i- ..


acanfi s ~''P - t -. fin ':P; ce whil looklns ,_' r Ian int< r rna _ h _:~ %d with S I

matches I with I ,,"'ip', ill" f _ - wlill ]10 ,--in - I ,if an . ther intescr and man lib ., %d

'with 96. On [b,,~ 1 J_h, r hand i tb, inpn i

acanf " ps : ne pace matches %d,iil 5 I hen a "" " match th -, / in ':-"

~~ mnat s fng '. I"' h a sp ce in I_,~ Input, Ther . .n m: b I. ,scanf uts t ae spaee

back: the _/., 916 characters rems in t '-_'1 re I, I telL II~ ", all of slc,anf. To allo .

~IP' ces a ,t r the fir :t numb ~ r, we s ould use the f rma ',ttino- ~II td lId n in ead,

Allh:·uh call 01-' aoarif and p,r'intf m,.I,', t,pp I, limHar~ th re 8Ii lgnificant dif 'ere c'~ be" fen til c two un i In ~ i no -·D,g lb se di ences c n be hazarc ou ' t" th he lth of .1, liT -'IT lOT _ . -, ~

, 10""

Ole 1 ornm In rni t _"e Is n put & in fI'OIDi I' "'_ ia ],eI' in ,I "a]J I, printf::

1*** WR,Q G *** I

PR-'Q'-G-" AA'IM

II ; _" I' _,- ". ' " I __

f'lortuJlately,. tbis mista e L: fairly easy to spot: prin.tf will display all couple or odd-lcoking numbers insteadof the valu.c, or i and j.

Since acanf normally skip white-space character i when looking for dan items there s often no nee-d- fOf a formal string ro include characters ether than conversion ,- peciticattons. ] ncorrectly as uming (hal e;,can.f format strings should resemble pz Lnt.f Fornul' ,-trines-another common error-may cause :scanf to behave in une pected ways, Let's I lee what happen when Ul!C followlng call of acanf is e .ecuted:

-scan.f will first look for an integer in the input, which it store •. in the variable i. acanf "ill then try '[0 match a C!OOO']J18 WiUl [he next input I. haracrer, If the next input character is B .. pace" not a c'o,n1m,a,scnnf win terminate withoin reading a. value for j ,

Although pr'in t f format strings often end witll \-n- .. putting a new-line character at the end of a s>canf fonm~r ·tri_ng is usually a bad idea. 'to acanf. a new ... Iine character in a format string is equivalent to ,3 slpal~le': both caus .. ~' acanf to adV811&e to the next non-white-space character; FDr ,ex;amp,le-tf the format - tring i

u %d \.n ~~ se.an! win skip white space, read an integer then skip to the next 00'0- white-space character, A format string like this CnD cause an interactive program to, "hang , until the u· er enter a nonblank character;

To lllustrare Slcanf"5 ability to match patterns, consider til" problem of reading a fractionentered by the user .. fractions are cusromanh written in the Jorm numeratoridenomituuor. Instead at havi Elg [he u._ er ente r '[he numerator and denominator of a fraction as separate integers, acanf makes 1't POlS',; ~i ble ton~!:a~ the entire trac-

'to ion 'T- ~ ~ followine - 0" --1- g,1i'!i""'!i1 .. ,"'[ .. ~. ~ .' dds ~'. . fn ti .. :, i:1I'~ ',1' I'''' t. ,...l.~' '.' 'I'Q '~l - '"I " .'

_] .. II.~. ~ .n ..... ~1 luunl_e pr,gr,w,~c W.1U:!~1 at .s ,~wo rae .0IlS,,, hdll~fa._e,i:1 IJulS li.~cLnlq_ue.

init mai.n (v,oid)'


p'rintf ( II En.ter fi-['Slt fraetion: lin') i' scan'f ( I'~ %Id/ %·d Iir ~ l&numl , &denolml);

p:rintf (IIEn.:ter second frac"tion:. II) If acanf ( 11I~1%,dl "'ell II I 1&:n,um2, ,&de.n;om2) i'

zesu.Lt, num ;; numt *' de·nom2: + nu'm2 ,. dencnU;

IQ: Wh~ t doe Bcan,f d merle iopu .. '

.'.'.Q ....

!!!',. •

.. rill


oC'w num'ber;s .. 7. " , dec:mlil'llS I nlJmbers .' 1.1







Q&A 47

1"@Eult denom = denaml ... den,om2 I,


printf ("'Th'e sum is %d/%d\nli, J:esult num, :result_d,enom');

return 0 i

A ses: inn, with this progr en - ight hal}l, , tb .f ltowim ap' earan ie:

Ent.er 'first f'ract~on! 5/6 Enter a.e,cond f'ra,c.tion: ,3[4 The sum is 3B/24


I 'v 'e _', n the "1 een erlion u. - d tn _-,ead aod ' rite reaer .. Wh' t ~ lbe Idi-ffer~

, nee bet' 'en % i .and '%d,? (PI ,~"9. I

In a pr i nt f format string, then - no c ifferenc b [W n the two, sc,an_f rormat, tring, 'ITo', le[~, %d I an ont mat h an integer ritten in ecimal (base ] 0 I rorm hile :%-i can match an inte er xpr 'Lk'OO in octal -~, e .' I decinu -f b tadecims (base 'I. ,)~ Ifs n input numb F h u · a pr fix (a in 015:6) 'i tre .', it W an 101 . -'tal numb _ ro' if it bas ill lOX or OX prr ~ fix ,,', in OxS 6 ) %·i treats it as a 11 . x number; Using %i lDst!· aid of %'d ~o' read, number can ha e surprisin _ result if rbe user should accidentall put a at 'tile beginning of the, numbr. Because of rhi trap, I rre - :'mltl nd sti 1d -g "~ilh '%d:.

HII prin tf 't- e~~t-· '% ·1: t e b ~gin __ 'jng,f a eon ,0_ -1 len sn ,ci1icatL D b01 r ,3D, I print tI,~ '\ filiar cler:'

II pr Lnt.f enr ounter ,two consecutl ve % haracters in a format string, H prints a

ing le % character, For example i Lbl srat Jment

pr±ntf I( *'Net pro I it. ~ td.%1i\n", profit:);

mi,gb prin

'T- e '\t ~"cap .. ,uR o .. d ,to I .. ~ B '. printf to _~ 'c- .. --,ce 0 ',~.h Q~ .. L , 0-' . d,o Ino ho', f: april -._ b to '. ,arl. ? [p.

rou d if] ~ t; Th - effect f println _ \ t lsn ( d fined in ':, i _ d. pe n ,. n iu t your oper I 'in, '.' 'item doe wh n asked I~ print a tab character, 'Tab stops ar . 'typic,aUy eight characters apart, but C males no guarantee.

nllmber but -


an ~ 3·-

I I' I .,-., . ,".. _',

ap ,1St , ... '

printf ,IIE,n'ter it DU,nW,er:, acanf ( I~ %dll~ f &i) i

In tiii., case, acanf reads the :2 and. 'the J,- toring 2 -, in i., The' remaining characters (f 00) ali' . 1,· It tOI be read by the next call 10 51 canf nr 'orne other input function), IOn the other hand" SUpplo51e that tile Input is invalid from tIl beginning:

In this case.jhe value of i is unde ined and foc is left for 'the ne, r aoanf ..

What cam we do about this sad t, te of affair ? Later we ,II ' ee how' tn te .. [

- . - ._ ,-_ , - - - ~ ---

dieteo1llnQ snum ill8caIlf '22~3whetble'r ~, call of ,sa;:.anf bas succe ded, If the leal] fails we can have the program

either termi na:R or try tOI recover, perhaps by ,dh,;c,~1dij ng the offending ill" I~J and asking the u er [01 try again, l 'Ways Ito discard bod input W~ discussed in the .. , see LiOD at tbe IC'IlU of Chapter 22,1)

Q: J do:n 'I' 'Ilnl~le stand ho,,' s:,canf ean ''"put 1b,81C:_}" ,ebAli~ ct ~r~1 B"D,d read tb,.cOI iB:',ain late'f~ [PI!! ,441]

A': As it turns out, prOgIB111S don It read user input IS it is typed Insu ad I input is stored in a hidden buffer to which scanf has access, It· I easy for sc'anf to put charaetors back into the "buffer for u- '!".cquent reading, IC'bacpller 22 IdisICDSSC, input buffering inmore detail"

Q'::Wbat do !u:"anf' d'ul if the U'., fir' puts PUDCt08ItiOiD, marks fcommas I for ,eu:mlB! ple be't.w,_en numbers .. '

A: Lei! '. 100k ,aIr ,3 simple e tample, Suppes e lblat we try t - read ,0, pai -' of integer using scanf:

prin'tf ( II Kn'tler l:w'o numbers: ");' scanf ( II %d%d,~II~, &i" &j)";

scanf wlllread tb,4 and 'tDre it in i. -, s it searches "for the beginning of the. sec ... ond number ,sean,£' e'n'COUJ11e'l"& the comma. Slnee number can't b gin with a comma, scan,f returns immediately, 'The COn1l:lL.1 and the second number are left tor the next cell of acanf.

01.1" IC'ODr,se,~, we can easily solve the problem by adding at comma to the format string if' we' fie sure 'dlaIt the numbers will alwav« be eparsted by a comma:

printf ( II Enter 't:wo nunibe,rs I se:p,arat.ed Jby d comma : ffill) ,;' acanf ( II 'd, 'd ~II ,f & i r &,'j);


- - - - ___,....

:Sectian 31l l'

1. Wh-lU[put do the fullc wing '- U I -fplrin~ . produce? ('a printf ( II. %6dtJ % 'dl~, 186 Ii 104(11';

(b print£ (mll%12 .. Se'li, 30.,253) 1

c) printf (11~%,"4fm~, aa , 1..'£i2) ;

(d) plrin.tf ( II '·_·6 . 2g Ilil I .000.00099179);

., -.- ri . I __ U ~'_ printf Iha~ di:.Ia; a f Loat; varir ble x in the foll,wlng f rma I~

31 Expon utial a ':I·j 11~ le ~ I~ju tifie in I _ nl Id D_" , . e 8'; 100 - I Ii, i't aft :f the d· cim:d point ..

I b) ponenrial notati n; nlllht jU5tUi'd in. it field! of i7J1! [0,0 sl . W, its after the decimal


(c) Fi ed decimal notation; left-ju tHied in 18 til 1d nf ize 'I~ thre dl, it ' 1 r the de imal point.

(d) I i-' -d decimal not; . i n; rlght-] __ ~ tified in a fi :]d I' i ·C! DO digi after (he decimal point,

- ~

~ or each ot til _-aUowin,g pair of scanf ormai trin,g I indicare 'wb th r or no- the two

tring· are equivalenr .. U'" they' - how bOiW rhe - can be distingui bed.

(it III %dlIIIIV' rTSU' ~II 'd III

fb) ~ !Sd~'d,-tdl'~ 'ver Ullc II %d - %:d ,",,"",'d!!

(Ie) III %-f '1'1

'd U if, ~~ f '!II

vef.:U .. I'I %if U

vers u. II~ %f ji %; f II

I! 4. Suppo se that w'e' call IS; canf a fon "',#I ': aoanf (.Ild'f%d~ ,&i" &x " &j) ,; If me user enter ..

10.3 51 6

wn;at will b th value I 1_ i. x I. nd jfter rhe CaD:, (. · ume th It i and j ar Lnt : ariables

andx is iii flo'a.e vari -bJe.)

I .' ... ·5,. Suppo e Ihar" call 's,c,anf a I ~. U .' ': acanf < 11 %f%,d%f ~I II &X t &i I' ,&y); if the user enters

12 3 . 5 ~I 10 7-8.: I

wb it will be th· valu. r f x, iii and 'Y- '. ar lib _ I all*. I~. sume tha -x and y are float '. '~. i~ able .and i i, .an Lnt; vari,a- le,

6. Show :bo,w to modify the a"dd~fra.e: .. c program 01' I.' ectien ~ ... ' "'0 that the u. 'er i allow _ [I I n~.:_r fracri ns thai :'Iontain spaces before and ner leach I :'h'-V3L. ' •

,:t:, lLarred exercs &;:J ar ui k~ -'the" rrect I, __ J·W ~r · ',[1 Uy nnl '1iI,le b ie us 101'; Read dru, question IJhnlroughly. rev~ew llbe' relevan eCl110n ~1~ 'nececs ary, and be cDJrefu U

Ie J • 'W'ntlS a prngrwn that accepts a date from the user in {be form 1J~"'1 / ddt)) ~\" ,:lndi then dispJay'· j ~ w n the form YY~ly'~1Jl'ldd;

Enter a ,date (mm/dd/yyyy): ~~/JJl /2'O~1 Y,QU ent.er'etl "the da'E_e 2Jll:L021?

2. Wri~e m IJfogf,am Juu furma,b; pruduct infomuuioJ1 entered 'lj.y the user; A session with lh, pnJgram should look like tbH~

inter It:e'ol number: 583

Enter unit price: 13. 5

Enter puz-chaae dat.e {mm/ddlyyyy}: 110/24/2010




$ 13,~ SID

Purch,ase D'ate) 1.0/2:4/2010


The itB~n number and date shoul d be ,lleft j ustified; the unit price should be right j ustified, Allew dollar amoun s up ~o $9999.9,9. Hinl!" Use tabs re Iine up the column".

CD .3. 8t111Uks are identified by Ian Internatlenal SUlndard Boo_k. NUfilber (]SB"Nt !SONs assigned after Janmu-y ~ 'I 200-1 'contain l3 digits, arranged 'in f ve ,gfOUp~ ·t sU'E:b as 97:8 O~3Y3~9'1'950-3,. (Older lSB'_:, use 10 digits.) The filsr group (1'be t;S I' 11'reful is ClUTfUl[!Y either 9']'8 IC't 9791, The lflvufl .idenrlfi(!;~" specifies 'tOO language 10[ country nf origin [for example, n and [ are' used in EU1iUs,h, .. , 'P6akinl countries). The pl!lblliShe,~ code identifles the publisher (39'3 is the code flDlf W., W. Norton), The ilelij luu1,tber is, assigned by nble '(lubli her [0 ide~--:ltify til peeific book 1(9'7950 is [be code, t~or thls bUBk)~ An I.SR. ends with a check digit that" s 111.;ed [0 -.eriJy the' accuracy of thepr,eced~nQ dlglrs, Write u _program [bat breaks . own ,;;ul1SBN entered by the' user:

En't.er ISBN = 97B:~la~39'J~97950-3 GS-l prefix~ 9'1B

Group id,entifi,er:: fJ

Publi B,h,er code ~ 3.$13

It,em n'u'mbler:: 9"950

Ch!e;!ek dig'it.: 3

Note: The Dlrm,'ber IO,f djgil In, each poop nu~:y vary: you can 't assurne Lha.L groups liul'vle the lengths shown in tJlis example, Tes~ your pm'gram with acLual1S.BN v,alues (U5111~Y fouod on the back co' or of a boot and on the c.opyright p'lage).

4_ Wr]t'e ,a program thai prompts the user to eater a telephone number [0 the term (xxx) X-J[X= x· xx arnd '[hen idls;phlY'S the number in '[he form XJt.X.XXi"UX:

Enter phone nuntber I[ (xxx) -xxx~xxxxJ; (4014)' 817-6900 y'ou '8nt;er,e,d ,404.,91'7.,690(:)

5,.Wdte a program tllst asks the user to enter [he ntlmber', from I LO 1, (l (in ,any order) and tbeD displays tile nurn ers Ina -, by 4 arrange men t, followed by [he ,- urns a -- the m'w~,~, columns and ·dlagonaJs~

En.'tar t.he numb:ers fixom lto 16 in an.y order:, 16 3 2 ~3 5 10 11 B 9 6 7 13 4 15 14 1

16 3 :2 13
5 10 11 B
9 6 7 12
4 is 14, 1
".. Row srums ~ 34 3,4 34. 3 'Column sums: 3 ~ 34 34 3" D1iagonal aums . 3, 34

If the row column, and di -,ln~ l surns , _ _ .11 til same I 'S lb" are ir this ex mple), he numbe - ar ,aid II IOIID. m« ' ;'flR'tm:~- he' m"ngmic.:·'4!lIW-e "JU',- IJI here appear ina 1514 engraving b ,arb '[ ,iud ~=1la.tb,n1aril 'ian' J -,_ ~,t:hLDiirer.·.;l th I the middl II1UDlber' in the

hi',' n ive the d __ te .,' 'the ngra ~ ,g I

l.dify th a,ddfrac. c pregram same ljme,epanned by I~ plus '. ign:

Bn'l er t'w,o fr c' .Lona ,se,parated hy a plu6 sign; 5/6 'JJL'4 The sum is 3,8/2.4

I) Ur i the user nter both fraction ',1 11-

Sign up to vote on this title
UsefulNot useful