版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C++ProgrammingChapter2I/OStreamsasanintroductiontoObjectsandClassesIndex
2.1StreamsandBasicFileI/O
2.2ToolsforstreamsI/O
2.3CharacterI/O
2.4InheritanceChap.2I/OStreams2.1StreamsandBasicFileI/OStreamsandbasicfileI/O
Streamsallowyoutowriteprogramsthathandlefileinputandkeyboardinputinaunifiedway,andthathandlefileoutputandscreenoutputinaunifiedway.
Astreamisaflowofcharacters.Iftheflowisintoyourprogram,thestreamiscalledaninputstream.Iftheflowisoutofyourprogram,thestreamiscalledoutputstream.
Iftheinputstreamflowsfromthekeyboard,thenyourprogramwilltakeinputfromthekeyboard.Iftheinputstreamflowsfromafile,thenyourprogramwilltakeitsinputfromthatfile.It’sSimilartooutputstream.StreamsandbasicfileI/O
Thecinisaninputstreamconnectedtothekeyboard,andcoutisanoutputstreamconnectedtothescreen.
Wecandefineotherstreamsthatcomefromorgotofiles;oncewehavedefinedthem,wecanusetheminthesamewayweusethestreamscinandcout.Forexample,astreamcalledin_streamisdefinedthatcomesfromsomefile:intthe_number;in_stream>>the_number;Anoutputstreamnamedout_streamisdefinedthatgoestoanotherfile:out_stream<<"the_numberis"<<the_number<<endl;
Oncethestreamsareconnectedtothedesiredfiles,yourprogramcandofileI/OthesamewayitdoesI/Ousingthekeyboardandscreen.WhyusefilesforI/O
Filesprovideyouwithawaytostoredatapermanently;
Youcancreateaninputfileforyourprogramorreadanoutputfileproducedbyyourprogramwheneverit’sconvenientforyou,asopposedtohavingtodoallyourreadingandwritingwhiletheprogramisrunning;
Filesalsoprovideyouwithaconvenientwaytodealwithlargequantitiesofdata.FileI/O
Whenyourprogramtakesinputfromafile,it’ssaidtobereadingfromthefile;whenyourprogramsendsoutputtoafile,it’ssaidtobewritingtothefile;
Themethodwewillusereadsthefilefromthebeginningtotheend.Usingthismethod,yourprogramisn’tallowedtobackupandreadanythinginthefileasecondtime,liketheoutputtothescreen.FileI/O
Thestreamscinandcoutarealreadydeclaredforyou,butifyouwantastreamtoconnectafile,youmustdeclareitjustasyouwoulddeclareanyothervariable.
Thetypeforinput-filestreamvariablesisnamedifstream,andthetypeforoutput-filestreamvariablesisnamedofstream.ifstreamin_stream;ofstreamout_stream;
Thetypesifstreamandofstreamaredefinedinthelibrarywiththeheaderfilefstream.#include<fstream>usingnamespacestd;FileI/O
Streamvariablesmusteachbeconnectedtoafile.Thisiscalledopeningthefileandisdonewithafunctionnamedopen.in_stream.open("infile.dat");
Iftheinputfileisinthesamedirectoryasyourprogram,youprobablycansimplygivethenameofthefile.Insomesituationsyoumightalsotospecifythedirectorythatcontainsthefile.FileI/O
Onceyouhavedeclaredaninputstreamvariableandconnectedittoafileusingtheopenfunction,yourprogramcantakeinputfromthefileusingtheextractionoperator>>.intone_number,another_number;in_stream>>one_number>>another_number;
Anoutputstreamisusedasthesamewayoftheinputstream.ofstreamout_stream;out_stream.open("outfile.dat");out_stream<<"one_number="<<one_number<<"another_number="<<another_number;FileI/O
Everyfileshouldbeclosedwhenyourprogramisfinishedgettinginputfromthefileorsendingoutputtothefile.Closingafiledisconnectsthestreamfromthefile.Afileisclosedwithacalltothefunctionclose.in_stream.close();out_stream.close();Checkwhetherafilewasopensuccessfully
Youcanusethememberfunctionnamedfailtotestwhetherastreamoperationhasfailed.Thereisamemberfunctionnamedfailforeachoftheclassesifstreamandofstream.
Youshouldplaceacalltofailimmediatelyaftereachcalltoopentocheckwhetherafilewasopenedsuccessfully,thefunctionfailwillreturntrueifthecalltoopenfails.in_stream.open("stuff.dat");if(in_stream.fail()){cout<<"Inputfileopenningfailed.\n";exit(1);}Chap.2I/OStreams2.2ToolsforstreamsI/OFormattingoutputwithstreamfunctions
Thelayoutofaprogram’soutputiscalledtheformatoftheoutput.
InC++youcancontroltheformatwithcommandsthatdeterminesuchdetailsasthenumberofspacesbetweenitemsandthenumberofdigitsafterthedecimalpoint.cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);Formattingoutputwithstreamfunctions
Everyoutputstreamhasamemberfunctionnamedprecision.Whenyourprogramexecutesacalltoprecision,thenfromthatpointoninyourprogram,anynumberwithadecimalpointthatisoutputtothatstreamwillbewrittenwithatotaloftwosignificantfigures,ofwithtwodigitsafterthedecimalpoint,dependingonwhenyourcompilerwaswritten.
Acalltoprecisionappliesonlytothestreamnamedinthecall.Ifyourprogramhasanotheroutputstreamout_stream_two,thenyouhavetocallthefunctionprecisiontoeffectonit.out_stream_two.precision(3);Formattingoutputwithstreamfunctions
setfisanabbreviationforsetflags.Aflagisaninstructiontodosomethinginoneoftwopossibleways.Ifaflagisgivenasanargumenttosetf,thentheflagtellsthecomputertowriteoutputtothatstreaminsomespecificway.Whatitcausesthestreamtododependsontheflag.
Anyflagthatissetmaybeunset.Tounsetaflag,youusethefunctionunsetf.cout.unsetf(ios::fixed);FormattingoutputwithstreamfunctionsFormattingFlagsforsetfFlagMeaningios::fixedFloating-pointnumbersarenotwrittenine-notationios::scientificios::showpointFloating-pointnumbersarewrittenine-notationAdecimalpointandtrailingzerosarealwaysshownforfloating-pointnumbersios::showposios::rightAplussignisoutputbeforepositivevaluesThenextitemoutputwillbeattherightendofthespacespecifiedbywidthios::leftThenextitemoutputwillbeattheleftendofthespacespecifiedbywidthFormattingoutputwithstreamfunctions
Oneverycommonlyusedformattingfunctioniswidth.cout<<"StartNow";cout.width(4);cout<<7<<endl;Theoutputis:StartNow7
Iftheoutputrequiredmorespacethanyouspecifiedintheargumenttowidth,thenasmuchadditionalspaceasisneededwillbeused.
Acalltowidthappliesonlytothenextitemthatisoutput.Ifyouwanttooutput12numbers,using4spacestooutputeachnumber,thenyoumustcallwidth12times.Manipulators
Amanipulatorisafunctionthatiscalledinanontraditionalway.Inturn,themanipulatorfunctioncallsamemberfunction.
Manipulatorsareplacedaftertheinsertionoperator<<,justasifmanipulatorfunctioncallwereanitemtobeoutput.
Liketraditionalfunctions,manipulatorsmayormaynothavearguments.
Tousethemanipulators,youmustincludethefollowingdirectiveinyourprogram:#include<iomanip>usingnamespacestd;Manipulators
Inputandoutputcanbeformattedusingmanipulators.ManipulatorsEffectendlWritenewlineandflushoutputstreamdechexInputoroutputindecimalInputoroutputinhexadecimalInputoroutputinoctalSetfieldwidthtonMakecthefillcharacterLeftjustifyRightjustifyoctsetw(n)setfill(c)leftrightManipulatorsExample1:inti=91;cout<<"i="<<i<<"(decimal)\n";cout<<"i="<<oct<<i<<"(octal)\n";cout<<"i="<<hex<<i<<"(hexadecimal)\n";cout<<"i="<<dec<<i<<"(decimal)\n";Output:i=91(decimal)i=133(octal)i=5b(hexadecimal)i=91(decimal)ManipulatorsExample2:floata=1.05,b=10.15,c=200.87;cout<<setfill('*')<<setprecision(4);cout<<setw(10)<<a<<endl;cout<<setw(10)<<b<<endl;cout<<setw(10)<<c<<endl;Output:******1.05*****10.15*****200.9Checkingfortheendofafile
Whenyouwriteaprogramthattakesitsinputfromafile,youwilloftenwanttheprogramtoreadallthedatainthefile,forexampletocalculatetheaverageofallthenumbersinthefile.Soyouneedtocheckfortheendofafile.doublenext,sum=0;intcount=0;while(Therearestillnumberstodoublenext,sum=0;intcount=0;while(in_stream>>next){beread){sum+=next;count++;in_stream>>next;sum+=next;count++;}Theaverageissum/count.}Theaverageissum/count++;Chap.2I/OStreams2.3CharacterI/OCharacterI/O
Alldataisinputandoutputascharacterdata.Whenyourprogramoutputsthenumber10,it’sreallythetwocharacters‘1’and‘0’thatareoutput.
Howeveryourprogramiswritten,thecomputerhardwareisalwaysreadingthecharacters‘1’and‘0’,notthenumber10.Thisconversionbetweencharactersandnumbersisusuallydoneautomaticallysothatyouneednotthinkaboutsuchdetail.
C++providessomelow-levelfacilitiesforinputandoutputofcharacterdata.Theselow-levelfacilitiesincludenoautomaticconversions.Thememberfunctionsgetandput
Thefunctiongetallowsyourprogramtoreadinonecharacterofinputandstoreitinavariableoftypechar.Everyinputstream,whetheritisaninputfilestreamorthestreamcin,hasgetasamemberfunction.charnext_symbol;cin.get(next_symbol);
Whenyouusetheextractionoperator>>,somethingsaredoneforyouautomatically,suchasskippingblanks.Withthememberfunctionget,nothingisdoneautomatically.Thememberfunctionsgetandput
It’simportanttonotethatyourprogramcanreadanycharacterinthisway.Ifthenextinputcharacterisablankoranew-linecharacter‘\n’,usinggetwillnotskipoverthecharacter.charc1,c2,c3;cin.get(c1);cin.get(c2);cin.get(c3);Iftheinputis:ABCDThen:c1='A';c2='B';c3='\n';Thememberfunctionsgetandput
Onethingyoucandowiththememberfunctiongetistohaveyourprogramdetecttheendofaline.cout<<"EnteralineofinputandIwillechoit:\n";charsymbol;do{cin.get(symbol);cout<<symbol;}while(symbol!='\n');cout<<"That'sallforthisdemonstration";
Thememberfunctionputisanalogoustothememberfunctiongetexceptthatit’susedforoutputratherthaninput.Putallowsyourprogramtooutputonecharacter.ProgrammingexampleCheckinginput#include<iostream.h>voidget_int(int&);voidmain(){voidget_int(int&number){charans;do{intn;get_int(n);cout<<"finalvaluereadis="<<n<<endl;cout<<"Enterinputnumber:";cin>>number;cout<<"Youentered"<<number<<"Isthatcorrect?}voidnew_line(){(yes/no):";cin>>ans;new_line();}while((ans!='Y')&&(ans!='y'));charsymbol;do{}cin.get(symbol);}while(symbol!='\n');}Theeofmemberfunction
Everyinput-filestreamhasamemberfunctioncalledeofthatcanbeusedtodeterminewhenallofthefilehasbeenreadandthereisnomoreinputleftfortheprogram.
Sinceweusuallywanttotestthatwearenotattheendofafile,acalltotheeofistypicallyusedwithanotinfrontofit.Exampleone:if(!fin.eof())cout<<"Notdoneyet.";elsecout<<"Endofthefile.";Exampletwo:in_stream.get(next);while(!in_stream.eof()){cout<<next;in_stream.get(next);}Chap.2I/OStreams2.4InheritanceInheritanceamongstreamclasses
Boththepredefinedstreamcinandaninput-filestreamareinputstreams,soinsomesensetheyaresimilar.
Theclassifstreamandistreamaredifferentbutcloselyrelatedtypes.Theclassifstreamisaderivedclassoftheclassistream.Inheritanceamongstreamclasses
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 四川省巴中市恩阳区2025届中考三模生物试题含解析
- GB/T 45168-2024保健食品中吡啶甲酸铬的测定
- A证(企业负责人)-安全员A证考试模拟题练习
- 沪科版九年级物理全一册《第十七章从指南针到磁浮列车》章末测试卷含答案
- 国企工会换届上的领导讲话-凝聚奋进力量 彰显工会作为
- 科技孵化器入驻企业潜力筛选
- 电力系统设备故障预防与处理流程
- 高一化学二第三章有机化合物练习
- 2024届安徽省示范高中培优联盟高考化学三模试卷含解析
- 2024高中地理第3章地理信息技术应用第2节遥感技术及其应用学案湘教版必修3
- 艺术品捐赠协议
- 网络安全系统运维方案
- 2024年标准沟渠回填工程承包协议版B版
- 2024年专用:物业安全管理协议3篇
- 【公开课】同一直线上二力的合成+课件+2024-2025学年+人教版(2024)初中物理八年级下册+
- 《政府采购业务培训》课件
- 《医疗器械召回管理办法》培训2024
- 网络安全培训内容课件
- 通信线路维护安全培训
- 专业微信小程序开发协议范例版
- 高职组全国职业院校技能大赛(婴幼儿照护赛项)备赛试题库(含答案)
评论
0/150
提交评论