收藏 分销(赏)

C--程序设计教学课件:Chapter-2-IO-Streams.pptx

上传人:二*** 文档编号:12598587 上传时间:2025-11-08 格式:PPTX 页数:36 大小:99.27KB 下载积分:5 金币
下载 相关 举报
C--程序设计教学课件:Chapter-2-IO-Streams.pptx_第1页
第1页 / 共36页
本文档共36页,全文阅读请下载到手机保存,查看更方便
资源描述
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.1StreamsandBasicFileI/O,StreamsandbasicfileI/O,Streamsallowyoutowriteprogramsthathandlefileinput,andkeyboardinputinaunifiedway,andthathandlefile,outputandscreenoutputinaunifiedway.,Astream,isaflowofcharacters.Iftheflowisintoyour,program,thestreamiscalledan,inputstream,.Iftheflowis,outofyourprogram,thestreamiscalled,outputstream,.,Iftheinputstreamflowsfromthekeyboard,thenyour,programwilltakeinputfromthekeyboard.Iftheinput,streamflowsfromafile,thenyourprogramwilltakeits,inputfromthatfile.ItsSimilartooutputstream.,StreamsandbasicfileI/O,Thecinisaninputstreamconnectedtothekeyboard,and,coutisanoutputstreamconnectedtothescreen.,Wecandefineotherstreamsthatcomefromorgotofiles;,oncewehavedefinedthem,wecanusetheminthesame,wayweusethestreamscinandcout.,Forexample,astreamcalledin_streamisdefinedthatcomes,fromsomefile:,intthe_number;,in_streamthe_number;,Anoutputstreamnamedout_streamisdefinedthatgoesto,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,Everyfileshouldbeclosedwhenyourprogramis,finishedgettinginputfromthefileorsending,outputtothefile.Closingafiledisconnectsthe,streamfromthefile.Afileisclosedwithacallto,thefunction,close,.,in_stream.close();,out_stream.close();,Checkwhetherafilewasopensuccessfully,Youcanusethememberfunctionnamed,fail,totest,whetherastreamoperationhasfailed.Thereisamember,functionnamed,fail,foreachoftheclasses,ifstream,and,ofstream,.,Youshouldplaceacalltofailimmediatelyaftereachcallto,opentocheckwhetherafilewasopenedsuccessfully,the,functionfailwillreturntrueifthecalltoopenfails.,in_stream.open(stuff.dat);,if(in_stream.fail(),coutInputfileopenningfailed.n;,exit(1);,Chap.2I/OStreams,2.2ToolsforstreamsI/O,Formattingoutputwithstreamfunctions,Thelayoutofaprogramsoutputiscalledthe,format,oftheoutput.,InC+youcancontroltheformatwith,commandsthatdeterminesuchdetailsasthe,numberofspacesbetweenitemsandthenumber,ofdigitsafterthedecimalpoint.,cout.setf(ios:fixed);,cout.setf(ios:showpoint);,cout.precision(2);,Formattingoutputwithstreamfunctions,Everyoutputstreamhasamemberfunctionnamed,precision,.Whenyourprogramexecutesacallto,precision,thenfromthatpointoninyourprogram,anynumberwith,adecimalpointthatisoutputtothatstreamwillbewritten,withatotaloftwosignificantfigures,ofwithtwodigits,afterthedecimalpoint,dependingonwhenyourcompiler,waswritten.,Acallto,precision,appliesonlytothestreamnamedinthe,call.Ifyourprogramhasanotheroutputstream,out_stream_two,thenyouhavetocallthefunction,precision,toeffectonit.,out_stream_two.precision(3);,Formattingoutputwithstreamfunctions,setf,isanabbreviationforsetflags.A,flag,isaninstructionto,dosomethinginoneoftwopossibleways.Ifaflagisgiven,asanargumentto,setf,thentheflagtellsthecomputerto,writeoutputtothatstreaminsomespecificway.Whatit,causesthestreamtododependsontheflag.,Anyflagthatissetmaybeunset.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,Adecimalpointandtrailingzerosarealways,shownforfloating-pointnumbers,ios:showpos,ios:right,Aplussignisoutputbeforepositivevalues,Thenextitemoutputwillbeattherightendof,thespacespecifiedbywidth,ios:left,Thenextitemoutputwillbeattheleftendofthe,spacespecifiedbywidth,Formattingoutputwithstreamfunctions,Oneverycommonlyusedformattingfunctionis,width,.,coutStartNow;,cout.width(4);,cout7endl;,Theoutputis:,StartNow7,Iftheoutputrequiredmorespacethanyouspecifiedinthe,argumentto,width,thenasmuchadditionalspaceasis,neededwillbeused.,Acalltowidthappliesonlytothenextitemthatisoutput.,Ifyouwanttooutput12numbers,using4spacestooutput,eachnumber,thenyoumustcallwidth12times.,Manipulators,A,manipulator,isafunctionthatiscalledina,nontraditionalway.Inturn,themanipulatorfunctioncalls,amemberfunction.,Manipulators,areplacedaftertheinsertionoperator,justasifmanipulatorfunctioncallwereanitemtobe,output.,Liketraditionalfunctions,manipulatorsmayormaynot,havearguments.,Tousethemanipulators,youmustincludethefollowing,directiveinyourprogram:,#include,usingnamespacestd;,Manipulators,Inputandoutputcanbeformattedusingmanipulators.,Manipulators,Effect,endl,Writenewlineandflushoutputstream,dec,hex,Inputoroutputindecimal,Inputoroutputinhexadecimal,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(hexadecimal),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,CharacterI/O,Alldataisinputandoutputas,characterdata,.Whenyour,programoutputsthenumber10,itsreallythetwo,characters1and0thatareoutput.,Howeveryourprogramiswritten,thecomputerhardware,isalwaysreadingthecharacters1and0,notthe,number10.Thisconversionbetweencharactersand,numbersisusuallydoneautomaticallysothatyouneednot,thinkaboutsuchdetail.,C+providessome,low-levelfacilities,forinputandoutput,ofcharacterdata.Theselow-levelfacilitiesincludeno,automaticconversions.,Thememberfunctionsgetandput,Thefunction,get,allowsyourprogramtoreadin,onecharacterofinputandstoreitinavariableof,typechar.Everyinputstream,whetheritisan,inputfilestreamorthestreamcin,has,get,asa,memberfunction.,charnext_symbol;,cin.get(next_symbol);,Whenyouusetheextractionoperator,some,thingsaredoneforyouautomatically,suchas,skippingblanks.Withthememberfunction,get,nothingisdoneautomatically.,Thememberfunctionsgetandput,Itsimportanttonotethatyourprogramcanreadany,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,Onethingyoucandowiththememberfunction,get,isto,haveyourprogram,detecttheendofaline,.,coutEnteralineofinputandIwillechoit:n;,charsymbol;,do,cin.get(symbol);,coutsymbol;,while(symbol!=n);,coutThatsallforthisdemonstration;,Thememberfunctionputisanalogoustothemember,functiongetexceptthatitsusedforoutputratherthan,input.Putallowsyourprogramtooutputonecharacter.,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);,Theeofmemberfunction,Everyinput-filestreamhasamemberfunctioncalled,eof,thatcanbe,usedtodeterminewhenallofthefilehasbeenreadandthereisno,moreinputleftfortheprogram.,Sinceweusuallywanttotestthatwearenotattheendofafile,acall,tothe,eof,istypicallyusedwithanotinfrontofit.,Exampleone:,if(!fin.eof(),coutNotdoneyet.;,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,itmeansthatclassAhasallthefeaturesof,classBbutitalsohasaddedfeatures.,Anystreamthatisoftype,ifstream,isalsoofthetype,istream,soaformalparameteroftype,istream,canbe,replacedbyanargumentoftype,ifstream,inafunctioncall.,Ifyoudefineafunctionwithaparameteroftype,istream,thenthatparametercanuseonly,istream,member,functions.Inparticular,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);,
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 教育专区 > 初中其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2025 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服