版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
“TheCProgrammingLanguage",2ndedition,
KernighanandRitchie《c程序設(shè)計(jì)語言》英文的配套答案,所列頁碼均為英文版的。1.011.021.031.041,051.061.071.081.091.101.111.12131.141.151.161.171.181.191.201.211.221.231.24TOC\o"1-5"\h\z01 2.02 2. 03 2.04 2.05 2.06 2.07 2.08 2. 09 2.10 3.01 3. 0203 3.04 3. 05 3.06 4.01 4.02 4.03 4.04 4. 05 4.06 4.07 4. 0812 4.13 4.14 5.01 5.02 5.03 5.04 5.05 5. 06 5.07 5.08 5. 0910 5.11 5.13 5.14 6.01 6.03 6.04 6.05 7. 01 7.02 7.03 7. 067.08 7.09 8. 01 8.03 8.04 8.06AnswertoExercise1-1Runthehello,world"programonyoursystem.Experimentwithleavingoutpartsoftheprogram,toseewhaterrormessagesyouget.Murphy,sLawdictatesthatthereisnosinglecorrectanswertotheveryfirstexerciseinthebook.Ohwell.Here,sa"helloworld"program:#include<stdio.h>intmain(void)(printf("hello,world\n");return0;)Asyoucansee,Vveaddedareturnstatement,becausemainalwaysreturnsint,andit'sgoodstyletoshowthisexplicitly.AnswertoExercise1-2Experimenttofindoutwhathappenswhenprintf,sargumentstringcontains\c,wherecissomecharacternotlistedabove.By'above',thequestionisreferringto:\n(newline)\t(tab)\b(backspace)ヽ”(doublequote)\\(backslash)Wehavetotreadcarefullyhere,becauseusinganon-specifiedescapesequenceinvokesundefinedbehaviour.Thefollowingprogramattemptstodemonstrateallthelegalescapesequences,notincludingtheonesalreadyshown(except\n,whichIactuallyneedintheprogram),andnotincludinghexadecimalandoctalescapesequences.^include<stdio.h>intmain(void)|printf(''Audibleorvisualalert.\a\n");printf("Formfeed.\f\n");printf("Thisescape,\r,movestheactivepositiontotheinitialpositionofthecurrentline.\n");printf("Verticaltab\vistricky,asitsbehaviourisunspecifiedundercertainconditions.\n");return0;AnswertoExercise1-3Modifythetemperatureconversionprogramtoprintaheadingabovethetable.^include<stdio.h>intmain(void)floatfahr,Celsius;intlower,upper,step;lower=0;upper=300;step=20;printf("F C\n\n〃);fahr=lower;while(fahr<=upper)(Celsius=(5.0/9.0)*(fahr-32.0);printf(,z%3.Of%6.fahr,Celsius);fahr=fahr+step;}return0;AnswertoExercise1-4WriteaprogramtoprintthecorrespondingCelsiustoFahrenheittable.^include<stdio.h>intmain(void)(floatfahr,Celsius;intlower,upper,step;lower=0;upper=300;step=20;printf("C F\n\n");Celsius=lower;while(celsius<=upper)(fahr=(9.0/5.0)*celsius+32.0;printfC%3.Of%6.lf\n",celsius,fahr);celsius=celsius+step;}return0;AnswertoExercise1-5Modifythetemperatoreconversionprogramtoprintthetableinreverseorder,thatis,from300degreesto0.Thisversionusesawhileloop:#include<stdio.h>intmain(void)(floatfahr,Celsius;intlower,upper,step;lower=0;upper=300;step=20;printf("C F'n\n");Celsius=upper;while(celsius>=lower)(fahr=(9.0/5.0)*celsius+32.0;printfC%3.Of%6.lf\n",celsius,fahr);celsius=celsius-step;)return0;Thisversionusesaforloop:#include<stdio.h>intmain(void)(floatfahr,celsius;intlower,upper,step;lower=0;upper=300;step=20;printf(Z/CF\n\n");for(celsius=upper;Celsius>=lower;Celsius=Celsius-step)(fahr=(9.0/5.0)*celsius+32.0;printf(z,%3.Of%6.lf\n”,celsius,fahr);}return0;ChrisSidinotesthatSection1.3HasashortForstatementexample,and“Basedonthatexample,Ithinkthesolutionto1.5:shoulddofahrtocelsiusconversion(whereasthesolutionsonyourpagedocelsiustofahr)shouldbesimilartotheexampleandassmall."Heoffersthissolution:#include<stdio.h>/*printFahrenheit-Celsiustable*/intmain()jintfahr;for(fahr=300;fahr>=0;fahr=fahr-20)printf("%3d%6.lf\n",fahr,(5.0/9.0)*(fahr-32));return0;AnswertoExercise1-6VerifythattheexpressiongetcharO!=EOFis0or1./*Thisprogrampromptsforinput,andthencapturesacharacter*fromthekeyboard.IfEOFissignalled(typicallythrougha*control-Dorcontrol-Zcharacter,thoughnotnecessarily),theprogramprints0.Otherwise,itprints1.*Ifyourinputstreamisbuffered(anditprobablyis),thenyouwillneedtopresstheENTERkeybeforetheprogramwill*respond.0include<stdio.h>intmain(void)|printf("Pressakey.ENTERwouldbenice:-)\n\n");printf("Theexpressiongetchar()!=EOFevaluatesto%d\n",getcharO!=EOF);return0;AnswertoExercise1-7WriteaprogramtoprintthevalueofEOF.#include<stdio.h>intmain(void)(printf("ThevalueofEOFis%d\n\n",EOF);return0;Exercise1-8Writeaprogramtocountblanks,tabs,andmain(void)(intblanks,tabs,newlines;intc;intdone=0;intlastchar=0;blanks=0;tabs=0;newlines=0;while(done==0)(c=getchar();if(c=…)++blanks;if(c=,\t')++tabs;if(c=='\n')++newlines;if(c==EOF)(if(lastchar!='\n,)(++newlines;/*thisisabitofasemanticstretch,butitcopes*withimplementationswhereatextfilemightnot*endwithanewline.ThankstoJimStadforpointing*thisout.*/)done=1;)lastchar=c;}printf("Blanks:%d\nTabs:%d\nLines:%d\n",blanks,tabs,newlines);return0;Exercise1-9Writeaprogramtocopyitsinputtoitsoutput,replacingeachstringofoneormoreblanksbyasingleblank.■include<stdio.h>intmain(void)(intc;intinspace;inspace=0;while((c=getchar())!=EOF)(if(c=='')(if(inspace==0)(inspace=1;putchar(c);))/*Wehaven'tmet'else'yet,sowehavetobealittleclumsy*/if(c!='')|inspace=0;putchar(c);}}return0;)ChrisSidiwrites:"insteadofhavingan"inspace"boolean,youcankeeptrackofthepreviouscharacterandseeifboththecurrentcharacterandpreviouscharacterarespaces:"#include<stdio.h>/*countlinesininput*/intmain(){intc,pc;/*c=character,pc=previouscharacter*//*setpctoavaluethatwouldn'tmatchanycharacter,incasethisprogramisevermodifiedtogetridofmultiplesofothercharacters*/pc=EOF;while((c二getchar())!=EOF){if(cニニ'')if(pc!二'')/*orif(pc!二c)*/putchar(c);/*Wehaven'tmet'else'yet,sowehavetobealittleclumsy*/if(c!二一)putchar(c);pc=c;)return0;Stigwrites:Iamhidingbehindthefactthatbreakismentionedintheintroduction!^include<stdio.h>intmain(void)(intc;while((c二getchar())!=EOF){
if(c=''){putchar(c);while((c=getcharO)==99&&c!=EOF)if(c==EOF)break;/*thebreakkeywordismentioned*intheintroduction...**/putchar(c);return0;Exercise1-10Writeaprogramtocopyitsinputtoitsoutput,replacingeachtabby\t,eachbackspaceby\b,andeachbackslashby\\.Thismakestabsandbackspacesvisibleinanunambiguousway.Category0GregoryPietschpointedoutthatmysolutionwasactuallyCategory1.Hewasquiteright.Betterstill,hewaskindenoughtosubmitaCategory0solutionhimself.Hereitis:/*GregoryPietsch<gkpl@>*//*Here'smyattemptataCategory0versionof1-10.*GregoryPietsch/#include<stdio.h>intmain()(intc,d;while((c=getchar())!=EOF)d=0;if(c=='\\'){putcharC\\*);d=1;)if(c=='、ピ){putcharC\\');putcharCt');d=1;}if(cニニ'、ド)(putcharC\\');putchar('b');d=1;}if(d==0)putchar(c);}return0;Category1Thissolution,whichIwrotemyself,isthesadlydiscreditedCat0answerwhichhasfoundanewleaseoflifeinCategory1.■include<stdio.h>#defineESC_CHAR'\\'intmain(void)iintc;while((c=getchar())!=EOF)switch(c)
case''b':/*TheOSonwhichItestedthis(NT)intercepts\bcharacters.putchar(ESCCHAR);putchar('b');break;case'\t':putchar(ESCCHAR);putchar(*t');break;caseESC_CHAR:putchar(ESC_CHAR);putchar(ESCCHAR);break;default:putchar(c);break;|)return0;Exercise1-11Howwouldyoutestthewordcountprogram?Whatkindsofinputaremostlikelytouncoverbugsifthereareany?Itsoundsliketheyarereallytryingtogettheprogrammerstolearnhowtodoaunittest.Iwouldsubmitthefollowing:0.inputinputinputinputinputfilefilefilefilefilecontainscontainscontainscontainscontainszerowords0.inputinputinputinputinputfilefilefilefilefilecontainscontainscontainscontainscontainszerowords1enormouswordwithoutanynewlinesallwhitespacewithoutnewlines66000newlinesword/{hugesequenceofwhitespaceofdifferentkinds}/wordinputinputinputinputinputfilefilefilefilefilecontainscontains66000singleletterwords,66inputinputinputinputinputfilefilefilefilefilecontainscontains66000singleletterwords,66totheline66000wordswithoutanynewlinesis/usr/dictcontents(orequivalent)isfullcollectionofmobywordsisbinary(e.g.itsownexecutable)10.inputfileis/dev/nul(orequivalent)66000ischosentocheckforintegraloverflowonsmallintegermachines.Dannsuggestsafollowupexercisel-lla:writeaprogramtogenerateinputs(0,1,2,3,4,5,6)IguessitwasinevitablethatI'dreceiveasolutionforthisfollowupexercise!HereisGregoryPietsch'sprogramtogenerateDann'ssuggestedinputs:^include<assert.h>■includeくstdio.h>intmain(void)(FILE*f;unsignedlongi;staticcharstaticchar/*Generate/*0.inputfstaticcharstaticchar/*Generate/*0.inputf=fopen("assert(f!=fclose(f);*ws=\i\t\v;*a!=abcdefghijk*i5="abcdef"nopqrs"abcdef"nopqrs"abcdefn\n;thefollowing:*/filecontainszerotestO","w");NULL);ghijk1mtuvwxyzghijk1mtuvwxyzghijk1mwords*//*1.inputfilecontains1enormouswordwithoutanynewlines*/f=fopen("testl","w");assert(f!=NULL);for(i=0;i<((66OOO11I/26)+1);i++)fputs(al,f);fclose(f);/*2.inputfilecontainsallwhitespacewithoutnewlines*/f=fopen(〃test2〃,〃w〃);assert(f!=NULL);for(i=0;i<((66OOO11I/4)+1);i++)fputs(ws,f);fclose(f);/*3.inputfilecontains66000newlines*/f=fopen(〃test3〃,"w");assert(f!=NULL);for(i=0;i<66000;i++)fputcC\n*,f);fclose(f);/*4.inputfilecontainsword/*{hugesequenceofwhitespaceofdifferentkinds)* /word*/f=fopen(〃test4","w");assert(f!=NULL);fputs("word”,f);for(i=0;i<((66OOO11I/26)+1);i++)fputs(ws,f);fputs("word",f);fclose(f);/*5.inputfilecontains66000singleletterwords,* 66totheline*/f=fopen("test5","w");assert(f!=NULL);for(i=0;i<1000;i++)fputs(i5,f);fclose(f);/*6.inputfilecontains66000wordswithoutanynewlines*/f=fopen("test6","w");assert(f!=NULL);for(i=0;i<66000;i++)fputs("word",f);fclose(f);return0;Exercise1-12Writeaprogramthatprintsitsinputonewordperline.#include<stdio.h>intmain(void)(intc;intinspace;inspace=0;while((c=getchar())!=EOF)(if(c==**IIc==>\t*||c==*\n)rIif(inspace==0)(inspace=1;putchar('\n');)/*else,don,tprintanything*/)else(inspace=0;putchar(c);))return0;Exercise1-13Writeaprogramtoprintahistogramofthelengthsofwordsinitsinput.Itiseasytodrawthehistogramwiththebarshorizontal;averticalorientationismorechallenging./*Thisprogramwasthesubjectofathreadincomp.lang,c,becauseofthewayithandledEOF.
Thecomplaintwasthat,intheeventofatextfiletslastlinenotendingwithanewline,thisprogramwouldnotcountthelastword.Iobjectedsomewhattothiscomplaint,onthegroundsthat“ifithasn'tgotanewlineattheendofeachline,itisn,tatextfile".*Thesegroundsturnedouttobeincorrect.Whethersuchafileisatextfileturnsouttobeimplementation-defined.I'dhadagoatcheckingmyfacts,andhad-asitturnsout一checkedthewrongfacts!(sigh)*Itcostmeanextravariable.Itturnedoutthattheleastdisturbingwaytomodifytheprogram(Ialwayslookfortheleastdisturbingway)wastoreplacethetraditionalwhile((c=getchar())!=EOF)withanEOFtestactuallyinsidetheloopbody.Thismeantaddinganextravariable,butisundoubtedlyworththecost,becauseitmeanstheprogramcannowhandleotherpeople'stextfilesaswellasmyown.AsBenPfaffsaidatthetime,"Beliberalinwhatyouaccept,strictinwhatyouproduce".Soundadvice.*Thenewversionhas,ofcourse,beentested,anddoesnowaccepttextfilesnotendinginnewlines.*Ihave,ofcourse,regeneratedthesampleoutputfromthisprogram.Actually,there'snoofcourse"aboutit-Inearlyforgot.*/#include<stdio.h>^defineMAXWORDLEN10intmain(void)intc;intinspace=0;longlengtharr[MAXWORDLEN+1];
intwordlen=0;intfirstletter=1;longthisval=0;longmaxval=0;intthisidx=0;intdone=0;for(thisidx=0;thisidx<=MAXWORDLEN;thisidx++){lengtharr[thisidx]=0;}while(done==0)(c=getchar();if(cニニ‘'||c=='\t'Ic=='\n'iIc=EOF)(if(inspace==0)(firstletter=0;inspace二1;if(wordlen<=MAXWORDLEN)(if(wordlen>0)(thisva!二++1engtharr[word1en-1];if(thisval>maxval)(maxval=thisval;)))else(thisval=++lengtharr[MAXWORDLEN];if(thisval>maxval)maxval二thisval;if(c==EOF)(done=1;)Ielse(if(inspace==1||firstletter=1)(wordlen=0;firstletter=0;inspace=0;)++wordlen;}}for(thisval=maxval;thisval>0;thisva!一一)(printf(線4d|",thisval);for(thisidx=0;thisidx<=MAXWORDLEN;thisidx++)(if(lengtharr[thisidx]>=thisval)(printf("*");}else{printf(" ");))printf("\n");}TOC\o"1-5"\h\zprintf(" +");for(thisidx=0;thisidx<=MAXWORDLEN;thisidx++)(printf(" ");)printf("\n ");for(thisidx=0;thisidx<MAXWORDLEN;thisidx++){printf("%2d",thisidx+1);printf(">%d\n",MAXWORDLEN);
return0;stheoutputoftheprogramwhengivenitsownsourceasinput:I*I*I*I*I*I*I*I*I*I*I*I*I*I*I*I*I*I*I*I**I**I**I**I**I**I**I**I**I**I**I**Here,11311211111010910810710610510410310210110099989796959493929190898887868584838281I**I**8079787776757473727170696867666564636261605958575655545352515049484746454443424140393837******************************************************************************************************************************************36*****35*****34*****33*****32*****31*****30******29******28*******27*******26*******25********24********23********22*********21*********20*********19*********18*********17*********16*********15*********14**********13**********12**********11**********10**********9***********8***********7***********6***********5***********4***********3***********2***********1***********+■12345678910>10Exercise1-14Writeaprogramtoprintahistogramofthefrequenciesofdifferentcharactersinitsinput.Naturally,I'vegoneforaverticalorientationtomatchexercise13.IhadsomedifficultyensuringthattheprintingoftheX-axisdidn'tinvolvecheating.Iwantedtodisplayeachcharacterifpossible,butthatwouldhavemeantusingisprint(),whichwehaven'tyetmet.SoIdecidedtodisplaythevalueofthecharacterinstead.(TheresultsbelowshowtheoutputonanASCIIsystem-naturally,arunonanEBCDICmachinewouldgivedifferentnumbers.)Ihadtojumpthroughafewhoopstoavoidusingthe%operatorwhich,again,wehaven'tyetmetatthispointinthetext.■include<stdio.h>/*NUM_CHARSshouldreallybeCHARMAXbutK&Rhaven'tcoveredthatatthisstageinthebook*/#defineNUM_CHARS256intmain(void)(intc;longfreqarr[NUMCHARS+1];longthisval=0;longmaxval=0;intthisidx=0;for(thisidx=0;thisidx<=NUMCHARS;thisidx++){freqarr[thisidx]=0;)while((c=getchar())!=EOF)(if(c<NUM_CHARS)(thisval=++freqarr[c];if(thisval>maxval)(maxval=thisval;
else(thisval=++freqarr[NUMCHARS];if(thisval>maxval)(maxval=thisval;)))for(thisval=maxval;thisval>0;thisval—)(printf廠%4dド,thisval);for(thisidx=0;thisidx<=NUMCHARS;thisidx++)(if(freqarr[thisidx]>=thisval)(printf("*");)elseif(freqarr[thisidx]>0)(printfCつ;)}printf("\n");)printf(/z +”);for(thisidx=0;thisidx<=NUM_CHARS;thisidx++)(if(freqarr[thisidx]>0)(printf(*-*);))printf(w\nつ;for(thisidx=0;thisidx<NUMCHARS;thisidx++)(if(freqarr[thisidx]>0)(printf("%d”,thisidx/100);printf("\nつ;for(thisidx=0;thisidx<NUM_CHARS;thisidx++)(if(freqarr[thisidx]>0)(printf('%d”,(thisidx-(100*(thisidx/100)))/10);})printf(*\n ");for(thisidx=0;thisidxくNUM-CHARS;thisidx++)(if(freqarr[thisidx]>0)(printf("知",thisidx-(10*(thisidx/10)));)if(freqarr[NUMCHARS]>0)(printf(り%d\n”,NUM_CHARS);)printf("\n");return0;Here'stheoutputoftheprogramwhengivenitsownsourceasinput:474I*473I*472I*471I*470I*469I*468I*467I*466I*465I*464I*463I*********************************************462461460459458457456455454453452451450449448447446445444443442441440439438437436435434433432431430429428427426425424423422421420419********************************************418417416415414413412411410409408407406405404403402401400399398397396395394393392391390389388387386385384383382381380379378377376375********************************************374373372371370369368367366365364363362361360359358357356355354353352351350349348347346345344343342341340339338337336335334333332331********************************************330329328327326325324323322321320319318317316315314313312311310309308307306305304303302301300299298297296295294293292291290289288287********************************************286285284283282281280279278277276275274273272271270269268267266265264263262261260259258257256255254253252251250249248247246245244243****************************************242241240239238237236235234233232231230229228227226225224223222221220219218217216215214213212211210209208207206205204203202201200199********************************************198197196195194193192191190189188187186185184183182181180179178177176175174173172171170169168167166165164163162161160159158157156155********************************************154153152151150149148147146145144143142141140139138137136135134133132131130129128127126125124123122121120119118117116115114113112111no109108107106105104103102101100999897969594939291908988878685848382818079787776757473727170696867***********************************************************************************************************************66****65****641****631****62****61****60****59*****58*****57*****56*****55*****54*****531*****521*****511******50******491*******481*******471*******46*******451*******44*******43********42**********41**********40************39*************38*************371*************361*************35*************341*************33*************32**************31*******ホ*******
**************************************6***************************************01*********************************************************************************************************************************************************1************1******************1*****************1**n**SI**SI**レI**SI**91**ZI**81**61**OSISss€SたSS9SZS8S6SOS*******************8******************************************7**6**51***********************************************************************41***************************************************3****************************************************2*****************************************************1**+- 000000000000000000000000000000000000000000000011111111111111111111111113333333444444444455555666666777777888899999990000000001111111111222220234578901234567890234901257902578923581235789012345789012345678901345AnswertoExercise1-15,page27RewritethetemperatureconversionprogramofSection1.2touseafunctionforconversion.■include<stdio.h>floatFtoC(floatf)floatc;c=(5.0/9.0)*(f-32.0);returnc;intmain(void)(floatfahr,Celsius;intlower,upper,step;lower=0;upper=300;step=20;printf(Z,F(xiàn)C\n\n");fahr=lower;while(fahr<=upper)(Celsius=FtoC(fahr);printf(zz%3.Of%6.lf\nzz,fahr,Celsius);fahr=fahr+step;)return0;AnswertoExercise1-16,page30Revisethemainroutineofthelongest-lineprogramsoitwillcorrectlyprintthelengthofarbitrarilylonginputlines,andasmuchaspossibleofthetext./include<stdio.h>Thisisthefirstprogramexercisewherethespecisn,tentirelyinclude<stdio.h>clear.Thespecsays,'Revisethemainroutine*,butthetruelengthofaninputlinecanonlybedeterminedbymodifyinggetline.Sothat*swhatwe'lldo.getlinewillnowreturntheactuallengthofthelineratherthanthenumberofcharactersreadintothearraypassedtoit.
ttdefineMAXLINE1000/*maximuminputlinesize*/intgetline(charline口,intmaxline);voidcopy(charto[],charfrom口);/*printlongestinputline*/intmain(void)intlen;intmaxintlen;intmax;/*/*currentmaximumlinelength*/lengthseensofar*/charline[MAXLINE]; /*currentinputline*/charlongest[MAXLINE];/*longestlinesavedhere*/max=0;while((len=getline(line,MAXLINE))>0)(printf(z,%d:%s〃,len,line);if(len>max)(max=len;copy(longest,line);))if(max>0)(printf(^Longestis%dcharacters:\n%s,z,max,longest);)printf(zz\nzz);return0;)/*getline:readalineintos,returnlength*/intgetline(chars[],int1im)(intc,i,j;for(i=0,j=0;(c=getchar())!=E0F&&c!='\n';++i)if(i<lim-1)s[j++]=c;if(c='\n)(if(i<=lim-1)(s[j++]=c;)++i;}s[j!=‘、〇';returni;}/*copy:copy'from'into'to';assume'to'isbigenough*/voidcopy(charto[],charfromロ)|inti;i=0;while((to[i]=from[i])!=‘、〇')(++i;ChrisSidi,however,wasnotconvinced-hethoughtthisanswerwas"tooeasy",sohecheckedwithbwk,whoagreed.Chriswrites:"LookslikeMr.Kernighanmeantfor"mainroutine"inExercise1-16torefertofunctionmain(),sayingyoursolutionofmodifyinggetlineOis"tooeasy.":)(ThoughIthinkyoursolutionshouldn'tberemovedfromtheAnswerswebsite,justcomplimentedwithanotheronethatonlymodifiesmain())"CueMr"386sx",ridingtotherescueonawhitehorse.../*Exercise1-16*/ttinclude<stdio.h>ttdefineMAXLINE20intgetline(chars[],intlim);voidcopy(charto[],charfromロ);intmain(void)(charline[MAXLINE];charlongest[MAXLINE];chartemp[MAXLINE];intlen,max,prevmax,getmore;max=prevmax=getmore=0;while((len=getline(line,MAXLINE))>0)(if(line[len-1]!='\n')(if(getmore==0)copy(temp,line);prevmax+=len;if(max<prevmax)max=prevmax;getmore=1;)else(if(getmore==1)(if(max<prevmax+len)(max=prevmax+len;copy(longest,temp);longest[MAXLINE-2]='\n';)getmore=0;)elseif(max<len)(max=len;copy(longest,line);)prevmax=0;if(max>0)printf('%s”,longest);printf(wlen=%d\n”,max);return0;intgetline(charsロ,int1im)(intc,i;for(i=0;iくlim-1&&((c=getcharO)!=EOF&&c!='\n');++i)s[i]=c;if(c=='\n'){s[i]=c;++i;)elseif(c==EOF&&i>0)(/*gottadosomethingaboutnonewlineprecedingEOF*/s[i]='\n,;++i;)s[i]='、0';returni;voidcopy(charto[],charfromロ)(inti;i=0;while((to[i]=from[i])!='\0')++i;AnswertoExercise1-17,page31Writeaprogramtoprintallinputlinesthatarelongerthan80characters.^include<stdio.h>#defineMINLENGTH81intreadbuff(char*buffer){size_tiニ〇;intc;while(i<MINLENGTH){c=getchar();if(c==EOF)return-1;if(cニニ'\nノreturn0;buffer[i++]二c;)return1;)intcopyline(char*buffer){size_ti;intc;intstatus=1;for(i=0;i<MINLENGTH;i++)putchar(buffer[i]);while(statusニニ1){c二getchar();if(c==EOF)status=-1;elseif(c=='\n')status二〇;elseputchar(c);)putchar('\n');returnstatus;)intmain(void){charbuffer[MINLENGTH];intstatus=0;while(status!=-1){status=readbuff(buffer);
if(status=1)status=copyline(buffer);return0;}AnswertoExercise1-18,page31Writeaprogramtoremovealltrailingblanksandtabsfromeachlineofinput,andtodeleteentirelyblanklines./*K&R21~18p31:Writeaprogramtoremovetrailingblanksandtabsfromeachlineofinput,andtodeleteentirelyblanklines.Theprogramspecificationisambiguous:does""entirelyblanklines”meanlinesthatcontainnocharactersotherthannewline,ordoesitincludelinescomposedofblanksandtabsfollowedbynewline?Thelatterinterpretationistakenhere.ThisimplementationdoesnotuseanyfeaturesnotintroducedinthefirstchapterofK&R2.Asaresult,itcan'tusepointerstodynamicallyallocateabuffertostoreblanksthatithasseen,soitmustlimitthenumberofblanksthatareallowedtooccurconsecutively.(ThisisthevalueofMAXQUEUE,minusone.)Itisintendedthatthisimplementation"degradesgracefully."Eventhoughaparticularinputmighthave1000ormoreblanksortabsinarow,causingaproblemforasinglepass,multiplepassesthroughthefilewillcorrecttheproblem.Theprogramsignalstheneedforsuchanadditionalpassbyreturningafailurecodetotheoperatingsystem.(EXIT_FAILUREisn'tmentionedinthefirstchapterofK&R,butI'mmakinganexceptionhere.)*/#include<stdio.h>^include<stdlib.h>#defineMAXQUEUE1001intadvance(intpointer)(if(pointer<MAXQUEUE-1)returnpointer+1;else
return0;intmain(void)(charblank[MAXQUEUE];inthead,tail;intnonspace;intretval;intc;retval=nonspace=head=tai1=0;while((c=getchar())!=EOF){if(c==>\n*){head=tail=0;if(nonspace)putchar('\n');nonspace=0;}elseif(cニニ‘'||c=='\t'){if(advance(head)ニニtai1){putchar(blank[tail]);tai!二advance(tail);nonspace=1;retval=EXIT_FAILURE;)blank[head]二c;head二advance(head);)else{while(head!=tail){putchar(blank[tail]);tai!二advance(tail);)putchar(c);nonspace二1;returnretval;ChrisSidiwrites:Ben,Ithoughtyoursolutionto1-18wasreallyneat(itdidn'toccurtomewhenIwasdoingtheexercise),thewayitdegradesgracefullyandmultiplepassescangetridofhugeblocksofwhitespace.However,ifthereisahugeblockofnon-trailingwhitespace(eg〃A〃,2000spaces,〃B\n〃)yourprogramreturnsanerrorwhenthere*snotaneedforit.Andifsomeoneweretouseyourprogramtillitpassesitwillloopinfinitely:$perl-e'print〃A",""x2000,〃B\n〃;'>in$until./a.out<in>out;doechofailed,runninganotherpass;cpoutin;donefailed,runninganotherpassfailed,runninganotherpassfailed,runninganotherpass[snip]BelowIhaveaddedavariablespaceJustPrintedtoyourprogramandchecktoseeifthespacesprintedearlyaretrailing.Ihopeyouliketheminorimprovement.(ThoughIcanunderstandifyoudon'tgivea[1]:))[1]expletivedeleted-RJH./*K&R21~18p31:Writeaprogramtoremovetrailingblanksandtabsfromeachlineofinput,andtodeleteentirelyblanklines.Theprogramspecificationisambiguous:does〃entirelyb
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 《高原疾病防治知識(shí)》課件
- 2025年分期付款化妝品購買合同
- 2025年P(guān)PP項(xiàng)目合作物資保障協(xié)議
- 二零二五年海洋工程建設(shè)項(xiàng)目施工合同6篇
- 二零二五年度PVC管材綠色制造技術(shù)合作合同3篇
- 2025年度新能源發(fā)電項(xiàng)目租賃合同3篇
- 2025版學(xué)校圖書館古籍保護(hù)與展示工程合同3篇
- 二零二五年度航空航天器研發(fā)與測試合同4篇
- 2025年度住宅小區(qū)物業(yè)管理權(quán)轉(zhuǎn)讓與社區(qū)安全防范協(xié)議
- 二零二五年度文化創(chuàng)意產(chǎn)業(yè)經(jīng)營授權(quán)協(xié)議
- 2024年云南省中考數(shù)學(xué)試題含答案解析
- 國家中醫(yī)藥管理局發(fā)布的406種中醫(yī)優(yōu)勢病種診療方案和臨床路徑目錄
- 2024年全國甲卷高考化學(xué)試卷(真題+答案)
- 汽車修理廠管理方案
- 人教版小學(xué)數(shù)學(xué)一年級(jí)上冊(cè)小學(xué)生口算天天練
- (正式版)JBT 5300-2024 工業(yè)用閥門材料 選用指南
- 三年級(jí)數(shù)學(xué)添括號(hào)去括號(hào)加減簡便計(jì)算練習(xí)400道及答案
- 蘇教版五年級(jí)上冊(cè)數(shù)學(xué)簡便計(jì)算300題及答案
- 澳洲牛肉行業(yè)分析
- 計(jì)算機(jī)江蘇對(duì)口單招文化綜合理論試卷
- 成人學(xué)士學(xué)位英語單詞(史上全面)
評(píng)論
0/150
提交評(píng)論