1、Click to edit Master title style,Click to edit Master text styles,Second level,Third level,Fourth level,Fifth level,11/7/2009,#,C+Programming,Chapter2I/OStreamsasan,introductiontoObjectsandClasses,Index,2.1StreamsandBasicFileI/O,2.2ToolsforstreamsI/O,2.3CharacterI/O,2.4Inheritance,Chap.2I/OStreams,2
2、1StreamsandBasicFileI/O,StreamsandbasicfileI/O,Streamsallowyoutowriteprogramsthathandlefileinput,andkeyboardinputinaunifiedway,andthathandlefile,outputandscreenoutputinaunifiedway.,Astream,isaflowofcharacters.Iftheflowisintoyour,program,thestreamiscalledan,inputstream,.Iftheflowis,outofyourprogram,
3、thestreamiscalled,outputstream,.,Iftheinputstreamflowsfromthekeyboard,thenyour,programwilltakeinputfromthekeyboard.Iftheinput,streamflowsfromafile,thenyourprogramwilltakeits,inputfromthatfile.ItsSimilartooutputstream.,StreamsandbasicfileI/O,Thecinisaninputstreamconnectedtothekeyboard,and,coutisanout
4、putstreamconnectedtothescreen.,Wecandefineotherstreamsthatcomefromorgotofiles;,oncewehavedefinedthem,wecanusetheminthesame,wayweusethestreamscinandcout.,Forexample,astreamcalledin_streamisdefinedthatcomes,fromsomefile:,intthe_number;,in_streamthe_number;,Anoutputstreamnamedout_streamisdefinedthatgoe
5、sto,anotherfile:,out_streamthe_numberisthe_number.,intone_number,another_number;,in_streamone_numberanother_number;,Anoutputstreamisusedasthesamewayoftheinput,stream.,ofstreamout_stream;,out_stream.open(outfile.dat);,out_streamone_number=one_number,another_number=another_number;,FileI/O,Everyfilesho
6、uldbeclosedwhenyourprogramis,finishedgettinginputfromthefileorsending,outputtothefile.Closingafiledisconnectsthe,streamfromthefile.Afileisclosedwithacallto,thefunction,close,.,in_stream.close();,out_stream.close();,Checkwhetherafilewasopensuccessfully,Youcanusethememberfunctionnamed,fail,totest,whet
7、herastreamoperationhasfailed.Thereisamember,functionnamed,fail,foreachoftheclasses,ifstream,and,ofstream,.,Youshouldplaceacalltofailimmediatelyaftereachcallto,opentocheckwhetherafilewasopenedsuccessfully,the,functionfailwillreturntrueifthecalltoopenfails.,in_stream.open(stuff.dat);,if(in_stream.fail
8、),coutInputfileopenningfailed.n;,exit(1);,Chap.2I/OStreams,2.2ToolsforstreamsI/O,Formattingoutputwithstreamfunctions,Thelayoutofaprogramsoutputiscalledthe,format,oftheoutput.,InC+youcancontroltheformatwith,commandsthatdeterminesuchdetailsasthe,numberofspacesbetweenitemsandthenumber,ofdigitsafterthe
9、decimalpoint.,cout.setf(ios:fixed);,cout.setf(ios:showpoint);,cout.precision(2);,Formattingoutputwithstreamfunctions,Everyoutputstreamhasamemberfunctionnamed,precision,.Whenyourprogramexecutesacallto,precision,thenfromthatpointoninyourprogram,anynumberwith,adecimalpointthatisoutputtothatstreamwillbe
10、written,withatotaloftwosignificantfigures,ofwithtwodigits,afterthedecimalpoint,dependingonwhenyourcompiler,waswritten.,Acallto,precision,appliesonlytothestreamnamedinthe,call.Ifyourprogramhasanotheroutputstream,out_stream_two,thenyouhavetocallthefunction,precision,toeffectonit.,out_stream_two.precis
11、ion(3);,Formattingoutputwithstreamfunctions,setf,isanabbreviationforsetflags.A,flag,isaninstructionto,dosomethinginoneoftwopossibleways.Ifaflagisgiven,asanargumentto,setf,thentheflagtellsthecomputerto,writeoutputtothatstreaminsomespecificway.Whatit,causesthestreamtododependsontheflag.,Anyflagthatiss
12、etmaybeunset.Tounsetaflag,youuse,thefunction,unsetf,.,cout.unsetf(ios:fixed);,Formattingoutputwithstreamfunctions,FormattingFlagsfor,setf,Flag,Meaning,ios:fixed,Floating-pointnumbersarenotwrittenine-,notation,ios:scientific,ios:showpoint,Floating-pointnumbersarewrittenine-notation,Adecimalpointandtr
13、ailingzerosarealways,shownforfloating-pointnumbers,ios:showpos,ios:right,Aplussignisoutputbeforepositivevalues,Thenextitemoutputwillbeattherightendof,thespacespecifiedbywidth,ios:left,Thenextitemoutputwillbeattheleftendofthe,spacespecifiedbywidth,Formattingoutputwithstreamfunctions,Oneverycommonlyus
14、edformattingfunctionis,width,.,coutStartNow;,cout.width(4);,cout7endl;,Theoutputis:,StartNow7,Iftheoutputrequiredmorespacethanyouspecifiedinthe,argumentto,width,thenasmuchadditionalspaceasis,neededwillbeused.,Acalltowidthappliesonlytothenextitemthatisoutput.,Ifyouwanttooutput12numbers,using4spacesto
15、output,eachnumber,thenyoumustcallwidth12times.,Manipulators,A,manipulator,isafunctionthatiscalledina,nontraditionalway.Inturn,themanipulatorfunctioncalls,amemberfunction.,Manipulators,areplacedaftertheinsertionoperator,justasifmanipulatorfunctioncallwereanitemtobe,output.,Liketraditionalfunctions,ma
16、nipulatorsmayormaynot,havearguments.,Tousethemanipulators,youmustincludethefollowing,directiveinyourprogram:,#include,usingnamespacestd;,Manipulators,Inputandoutputcanbeformattedusingmanipulators.,Manipulators,Effect,endl,Writenewlineandflushoutputstream,dec,hex,Inputoroutputindecimal,Inputoroutputi
17、nhexadecimal,Inputoroutputinoctal,Setfieldwidthton,Makecthefillcharacter,Leftjustify,Rightjustify,oct,setw(n),setfill(c),left,right,Manipulators,Example1:,inti=91;,couti=i(decimal)n;,couti=octi(octal)n;,couti=hexi(hexadecimal)n;,couti=deci(decimal)n;,Output:,i=91(decimal),i=133(octal),i=5b(hexadecim
18、al),i=91(decimal),Manipulators,Example2:,floata=1.05,b=10.15,c=200.87;,coutsetfill(*)setprecision(4);,coutsetw(10)aendl;,coutsetw(10)bendl;,coutsetw(10)cnext),beread),sum+=next;,count+;,in_streamnext;,sum+=next;,count+;,Theaverageissum/count.,Theaverageissum/count+;,Chap.2I/OStreams,2.3CharacterI/O,
19、CharacterI/O,Alldataisinputandoutputas,characterdata,.Whenyour,programoutputsthenumber10,itsreallythetwo,characters1and0thatareoutput.,Howeveryourprogramiswritten,thecomputerhardware,isalwaysreadingthecharacters1and0,notthe,number10.Thisconversionbetweencharactersand,numbersisusuallydoneautomaticall
20、ysothatyouneednot,thinkaboutsuchdetail.,C+providessome,low-levelfacilities,forinputandoutput,ofcharacterdata.Theselow-levelfacilitiesincludeno,automaticconversions.,Thememberfunctionsgetandput,Thefunction,get,allowsyourprogramtoreadin,onecharacterofinputandstoreitinavariableof,typechar.Everyinputstr
21、eam,whetheritisan,inputfilestreamorthestreamcin,has,get,asa,memberfunction.,charnext_symbol;,cin.get(next_symbol);,Whenyouusetheextractionoperator,some,thingsaredoneforyouautomatically,suchas,skippingblanks.Withthememberfunction,get,nothingisdoneautomatically.,Thememberfunctionsgetandput,Itsimportan
22、ttonotethatyourprogramcanreadany,characterinthisway.Ifthenextinputcharacterisablank,oranew-linecharactern,using,get,willnotskipoverthe,character.,charc1,c2,c3;,cin.get(c1);,cin.get(c2);,cin.get(c3);,Iftheinputis:,AB,CD,Then:,c1=A;c2=B;c3=n;,Thememberfunctionsgetandput,Onethingyoucandowiththememberfu
23、nction,get,isto,haveyourprogram,detecttheendofaline,.,coutEnteralineofinputandIwillechoit:n;,charsymbol;,do,cin.get(symbol);,coutsymbol;,while(symbol!=n);,coutThatsallforthisdemonstration;,Thememberfunctionputisanalogoustothemember,functiongetexceptthatitsusedforoutputratherthan,input.Putallowsyourp
24、rogramtooutputonecharacter.,ProgrammingexampleCheckinginput,#include,voidget_int(int,voidmain(),voidget_int(int&number),charans;,do,intn;,get_int(n);,coutfinalvaluereadis=,nendl;,coutnumber;,coutYouenterednumber,ans;,new_line();,while(ans!=Y),charsymbol;,do,cin.get(symbol);,while(symbol!=n);,Theeofm
25、emberfunction,Everyinput-filestreamhasamemberfunctioncalled,eof,thatcanbe,usedtodeterminewhenallofthefilehasbeenreadandthereisno,moreinputleftfortheprogram.,Sinceweusuallywanttotestthatwearenotattheendofafile,acall,tothe,eof,istypicallyusedwithanotinfrontofit.,Exampleone:,if(!fin.eof(),coutNotdoneye
26、t.;,else,coutEndofthefile.;,Exampletwo:,in_stream.get(next);,while(!in_stream.eof(),coutn1n2;,coutn1+n2=(n1+n2)n1n2;,coutn1+n2=(n1+n2)endl;,ifstreamfin;,two_sum(fin);,two_sum(cin);,Inheritanceamongstreamclasses,WhenwesaythatsomeclassAisa,derivedclass,ofsome,otherclassB,itmeansthatclassAhasallthefeat
27、uresof,classBbutitalsohasaddedfeatures.,Anystreamthatisoftype,ifstream,isalsoofthetype,istream,soaformalparameteroftype,istream,canbe,replacedbyanargumentoftype,ifstream,inafunctioncall.,Ifyoudefineafunctionwithaparameteroftype,istream,thenthatparametercanuseonly,istream,member,functions.Inparticula
28、r,itcannotusethefunction,open,and,close,.,Inheritanceamongstreamclasses,Theclass,ostream,istheclassofalloutputstreams.The,stream,output-filestream,classofstreamisaderivedclassoftheclassostream.,coutisoftypeostream.In,contrastto,cout,an,isdeclaredtobeoftype,ofstream,.The,voidsay_hello(ostream&any_out_stream),any_out_streamHello!;,ofstreamfout;,fout.open(afile.dat);,say_hello(cout);,say_hello(fout);,






