




已阅读5页,还剩96页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter6,I/OStreamsasanIntroductiontoObjectsandClasses,Slide6-3,Overview,6.1StreamsandBasicFileI/O6.2ToolsforStreamI/O6.3CharacterI/O,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,6.1,StreamsandBasicFileI/O,Slide6-5,I/OStreams,I/OreferstoprograminputandoutputInputisdeliveredtoyourprogramviaastreamobjectInputcanbefromThekeyboardAfileOutputisdeliveredtotheoutputdeviceviaastreamobjectOutputcanbetoThescreenAfile,Slide6-6,Objects,ObjectsarespecialvariablesthatHavetheirownspecial-purposefunctionsSetC+apartfromearlierprogramminglanguages,Slide6-7,StreamsandBasicFileI/O,FilesforI/OarethesametypeoffilesusedtostoreprogramsAstreamisaflowofdata.Inputstream:DataflowsintotheprogramIfinputstreamflowsfromkeyboard,theprogramwillacceptdatafromthekeyboardIfinputstreamflowsfromafile,theprogramwillacceptdatafromthefileOutputstream:DataflowsoutoftheprogramTothescreenToafile,Slide6-8,cinAndcoutStreams,cinInputstreamconnectedtothekeyboardcoutOutputstreamconnectedtothescreencinandcoutdefinedintheiostreamlibraryUseincludedirective:#includeYoucandeclareyourownstreamstousewithfiles.,Slide6-9,WhyUseFiles?,Filesallowyoutostoredatapermanently!DataoutputtoafilelastsaftertheprogramendsAninputfilecanbeusedoverandoverNotypingofdataagainandagainfortestingCreateadatafileorreadanoutputfileatyourconvenienceFilesallowyoutodealwithlargerdatasets,Slide6-10,FileI/O,ReadingfromafileTakinginputfromafileDonefrombeginningtotheend(fornow)Nobackinguptoreadsomethingagain(OKtostartover)JustasdonefromthekeyboardWritingtoafileSendingoutputtoafileDonefrombeginningtoend(fornow)Nobackinguptowritesomethingagain(OKtostartover)Justasdonetothescreen,Slide6-11,StreamVariables,Likeothervariables,astreamvariableMustbedeclaredbeforeitcanbeusedMustbeinitializedbeforeitcontainsvaliddataInitializingastreammeansconnectingittoafileThevalueofthestreamvariablecanbethoughtofasthefileitisconnectedtoCanhaveitsvaluechangedChangingastreamvaluemeansdisconnectingfromonefileandconnectingtoanother,Slide6-12,StreamsandAssignment,AstreamisaspecialkindofvariablecalledanobjectObjectscanusespecialfunctionstocompletetasksStreamsusespecialfunctionsinsteadoftheassignmentoperatortochangevalues,Slide6-13,DeclaringAnInput-fileStreamVariable,Input-filestreamsareoftypeifstreamTypeifstreamisdefinedinthefstreamlibraryYoumustusetheincludeandusingdirectives#includeusingnamespacestd;Declareaninput-filestreamvariableusingifstreamin_stream;,Slide6-14,DeclaringAnOutput-fileStreamVariable,Ouput-filestreamsofaretypeofstreamTypeofstreamisdefinedinthefstreamlibraryYoumustusetheseincludeandusingdirectives#includeusingnamespacestd;Declareaninput-filestreamvariableusingofstreamout_stream;,Slide6-15,Onceastreamvariableisdeclared,connectittoafileConnectingastreamtoafileisopeningthefileUsetheopenfunctionofthestreamobjectin_stream.open(infile.dat);,ConnectingToAFile,Slide6-16,UsingTheInputStream,Onceconnectedtoafile,theinput-streamvariablecanbeusedtoproduceinputjustasyouwouldusecinwiththeextractionoperatorExample:intone_number,another_number;in_streamone_numberanother_number;,Slide6-17,UsingTheOutputStream,Anoutput-streamworkssimilarlytotheinput-streamofstreamout_stream;out_stream.open(outfile.dat);out_streamonenumber=one_numberanothernumber=another_number;,Slide6-18,ExternalFileNames,AnExternalFileNameIsthenameforafilethattheoperatingsystemusesinfile.datandoutfile.datusedinthepreviousexamplesIsthereal,on-the-disk,nameforafileNeedstomatchthenamingconventionsonyoursystemUsuallyonlyusedinthestreamsopenstatementOnceopen,referredtousingthenameofthestreamconnectedtoit.,Afterusingafile,itshouldbeclosedThisdisconnectsthestreamfromthefileClosefilestoreducethechanceofafilebeingcorruptediftheprogramterminatesabnormallyItisimportanttocloseanoutputfileifyourprogramlaterneedstoreadinputfromtheoutputfileThesystemwillautomaticallyclosefilesifyouforgetaslongasyourprogramendsnormally,Slide6-19,Display6.1,ClosingaFile,Slide6-20,Objects,Anobjectisavariablethathasfunctionsanddataassociatedwithitin_streamandout_streameachhaveafunctionnamedopenassociatedwiththemin_streamandout_streamusedifferentversionsofafunctionnamedopenOneversionofopenisforinputfilesAdifferentversionofopenisforoutputfiles,Slide6-21,MemberFunctions,AmemberfunctionisafunctionassociatedwithanobjectTheopenfunctionisamemberfunctionofin_streaminthepreviousexamplesAdifferentopenfunctionisamemberfunctionofout_streaminthepreviousexamples,Slide6-22,ObjectsandMemberFunctionNames,ObjectsofdifferenttypeshavedifferentmemberfunctionsSomeofthesememberfunctionsmighthavethesamenameDifferentobjectsofthesametypehavethesamememberfunctions,Slide6-23,Classes,Atypewhosevariablesareobjects,isaclassifstreamisthetypeofthein_streamvariable(object)ifstreamisaclassTheclassofanobjectdeterminesitsmemberfunctionsExample:ifstreamin_stream1,in_stream2;in_stream1.openandin_stream2.openarethesamefunctionbutmighthavedifferentarguments,Slide6-24,ClassMemberFunctions,MemberfunctionsofanobjectarethememberfunctionsofitsclassTheclassdeterminesthememberfunctionsoftheobjectTheclassifstreamhasanopenfunctionEveryvariable(object)declaredoftypeifstreamhasthatopenfunction,Slide6-25,CallingaMemberFunction,CallingamemberfunctionrequiresspecifyingtheobjectcontainingthefunctionThecallingobjectisseparatedfromthememberfunctionbythedotoperatorExample:in_stream.open(infile.dat);,Slide6-26,MemberFunctionCallingSyntax,Syntaxforcallingamemberfunction:Calling_object.Member_Function_Name(Argument_list);,Slide6-27,ErrorsOnOpeningFiles,OpeningafilecouldfailforseveralreasonsCommonreasonsforopentofailincludeThefilemightnotexistThenamemightbetypedincorrectlyMaybenoerrormessageifthecalltoopenfailsProgramexecutioncontinues!,Slide6-28,CatchingStreamErrors,Memberfunctionfail,canbeusedtotestthesuccessofastreamoperationfailreturnsabooleantype(trueorfalse)failreturnstrueifthestreamoperationfailed,Slide6-29,HaltingExecution,Whenastreamopenfunctionfails,itisgenerallybesttostoptheprogramThefunctionexit,haltsaprogramexitreturnsitsargumenttotheoperatingsystemexitcausesprogramexecutiontostopexitisNOTamemberfunctionExitrequirestheincludeandusingdirectives#includeusingnamespacestd;,Immediatelyfollowingthecalltoopen,checkthattheoperationwassuccessful:in_stream.open(stuff.dat);if(in_stream.fail()coutthe_number;Theinputfilemustcontainexactlythedataexpected,OutputexamplessofarcreatenewfilesIftheoutputfilealreadycontainsdata,thatdataislostToappendnewoutputtotheendanexistingfileusetheconstantios:appdefinedintheiostreamlibrary:outStream.open(important.txt,ios:app);Ifthefiledoesnotexist,anewfilewillbecreated,Slide6-32,Display6.3,AppendingData(optional),Slide6-33,FileNamesasInput(optional),ProgramuserscanenterthenameofafiletouseforinputorforoutputProgrammustuseavariablethatcanholdmultiplecharactersAsequenceofcharactersiscalledastringDeclaringavariabletoholdastringofcharacters:charfile_name16;file_nameisthenameofavariableBracketsenclosethemaximumnumberofcharacters+1Thevariablefile_namecontainsupto15characters,charfile_name16;coutfile_name;ifstreamin_stream;in_stream.open(file_name);if(in_stream.fail()coutInputfileopeningfailed.n;exit(1);,Slide6-34,Display6.4(1),Display6.4(2),UsingACharacterString,Slide6-35,Section6.1Conclusion,CanyouWriteaprogramthatusesastreamcalledfinwhichwillbeconnectedtoaninputfileandastreamcalledfoutwhichwillbeconnectedtoanoutputfile?Howdoyoudeclarefinandfout?Whatincludedirective,ifany,doyouneetoplaceinyourprogramfile?Nameatleastthreememberfunctionsofaniostreamobjectandgiveexamplesofusageofeach?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,6.2,ToolsforStreamsI/O,Slide6-37,ToolsforStreamI/O,TocontroltheformatoftheprogramsoutputWeusecommandsthatdeterminesuchdetailsas:ThespacesbetweenitemsThenumberofdigitsafteradecimalpointThenumericstyle:scientificnotationforfixedpointShowingdigitsafteradecimalpointeveniftheyarezeroesShowingplussignsinfrontofpositivenumbersLeftorrightjustifyingnumbersinagivenspace,Slide6-38,FormattingOutputtoFiles,Formatoutputtothescreenwith:cout.setf(ios:fixed);cout.setf(ios:showpoint);cout.precision(2);Formatoutputtoafileusingtheout-filestreamnamedout_streamwith:out_stream.setf(ios:fixed);out_stream.setf(ios:showpoint);out_stream.precision(2);,Slide6-39,out_stream.precision(2);,precisionisamemberfunctionofoutputstreamsAfterout_stream.precision(2);Outputofnumberswithdecimalpointswillshowatotalof2significantdigits23.2.2e72.26.9e-10.00069ORwillshow2digitsafterthedecimalpoint23.562.26e72.210.690.69e-4Callstoprecisionapplyonlytothestreamnamedinthecall,Slide6-40,setf(ios:fixed);,setfisamemberfunctionofoutputstreamssetfisanabbreviationforsetflagsAflagisaninstructiontodooneoftwooptionsios:fixedisaflagAfterout_stream.setf(ios:fixed);AllfurtheroutputoffloatingpointnumbersWillbewritteninfixed-pointnotation,thewaywenormallyexpecttoseenumbersCallstosetfapplyonlytothestreamnamedinthecall,Afterout_stream.setf(ios:showpoint);OutputoffloatingpointnumbersWillshowthedecimalpointevenifalldigitsafterthedecimalpointarezeroes,Slide6-41,Display6.5,setf(ios:showpoint);,Slide6-42,(ios:right),(ios:left),CreatingSpaceinOutput,ThewidthfunctionspecifiesthenumberofspacesforthenextitemAppliesonlytothenextitemofoutputExample:Toprintthedigit7infourspacesuseout_stream.width(4);out_stream7endl;Threeofthespaceswillbeblank,Slide6-43,NotEnoughWidth?,Whatiftheargumentforwidthistoosmall?Suchasspecifyingcout.width(3);whenthevaluetoprintis3456.45TheentireitemisalwaysoutputIftoofewspacesarespecified,asmanymorespacesasneededareused,Slide6-44,UnsettingFlags,Anyflagthatisset,maybeunsetUsetheunsetffunctionExample:cout.unsetf(ios:showpos);causestheprogramtostopprintingplussignsonpositivenumbers,Slide6-45,Manipulators,AmanipulatorisafunctioncalledinanontraditionalwayManipulatorsinturncallmemberfunctionsManipulatorsmayormaynothaveargumentsUsedaftertheinsertionoperator()asifthemanipulatorfunctioncallisanoutputitem,Slide6-46,TwoSpaces,FourSpaces,ThesetwManipulator,setwdoesthesametaskasthememberfunctionwidthsetwcallsthewidthfunctiontosetspacesforoutputExample:coutStartsetw(4)10setw(4)setw(6)30;produces:Start102030,Slide6-47,ThesetprecisionManipulator,setprecisiondoesthesametaskasthememberfunctionprecisionExample:cout.setf(ios:fixed);cout.setf(ios:showpoint);cout$setprecision(2)10.3endl$20.5next)Readsavaluefromin_streamandstoresitinnextTrueifavaluecanbereadandstoredinnextFalseifthereisnotavaluetoberead(theendofthefile),Slide6-51,EndofFileExample,Tocalculatetheaverageofthenumbersinafiledoublenext,sum=0;intcount=0;while(in_streamnext)sum=sum+next;count+;doubleaverage=sum/count;,Slide6-52,StreamArgumentsandNamespaces,UsingdirectiveshavebeenlocaltofunctiondefinitionsintheexamplessofarWhenparametertypenamesareinanamespaceAusingdirectivemustbeoutsidethefunctionsoC+willunderstandtheparametertypenamessuchasifstreamEasysolutionistoplacetheusingdirectiveatthebeginningofthefileManyexpertsdonotapproveasthisdoesnotallowusingmultiplenamespaceswithnamesincommon,TheprograminDisplay6.6Takesinputfromrawdata.datWritesoutputtothescreenandtoneat.datFormattinginstructionsareusedtocreateaneaterlayoutNumbersarewrittenoneperlineinafieldwidthof12Eachnumberiswrittenwith5digitsafterthedecimalpointEachnumberiswrittenwithaplusorminussignUsesfunctionmake_neatthathasformalparametersfortheinput-filestreamandoutput-filestream,Slide6-53,Display6.6(1),Display6.6(2),Display6.6(3),ProgramExample,Slide6-54,Section6.2Conclusion,CanyouShowtheoutputproducedwhenthefollowinglineisexecuted?cout*setw(3)12345)whichperformssomeautomaticworkDoesnotskipblanks,Slide6-59,Usingget,Theselinesusegettoreadacharacterandstoreitinthevariablenext_symbolcharnext_symbol;cin.get(next_symbol);AnycharacterwillbereadwiththesestatementsBlankspacestoo!ntoo!(Thenewlinecharacter),Slide6-60,getSyntax,input_stream.get(char_variable);Examples:charnext_symbol;cin.get(next_symbol);ifstreamin_stream;in_stream.open(infile.dat);in_stream.get(next_symbol);,Slide6-61,MoreAboutget,Giventhiscode:charc1,c2,c3;cin.get(c1);cin.get(c2);cin.get(c3);andthisinput:ABCDc1=Ac2=Bc3=ncinc1c2c3;wouldplaceCinc3(theoperatorskipsthenewlinecharacter),Slide6-62,TheEndofTheLine,ToreadandechoalineofinputLookfornattheendoftheinputline:coutEnteralineofinputandIwillechoit.n;charsymbol;docin.get(symbol);coutandcin.get,Besuretodealwiththenthatendseachinputlineifusingcinandcin.getcinreadsuptothenThenremainsintheinputstreamUsingcin.getnextwillreadthenThenew_linefunctionfromDisplay6.7canbeusedtoclearthen,Slide6-73,TheDialogue:Enteranumber:21Nowenteraletter:A,TheResult:number=21symbol=n,nExample,TheCode:coutnumber;coutsymbol;,Slide6-75,AnothernFix,coutnumber;new_line();/FromDisplay6.7coutNowenteraletter:n;charsymbol;cin.get(symbol);,Slide6-76,DetectingtheEndofaFile,MemberfunctioneofdetectstheendofafileMemberfunctionofeveryinput-filestreameofstandsforendoffileeofreturnsabooleanvalueTruewhentheendofthefilehasbeenreachedFalsewhenthereismoredatatoreadNormallyusedtodeterminewhenweareNOTattheendofthefileExample:if(!in_stream.eof(),Slide6-77,Usingeof,Thisloopreadseachcharacter,andwritesittothescreenin_stream.get(next);while(!in_stream.eof()coutnext)while(!in_stream.eof()Whichshouldbeused?Ingeneral,useeofwheninputistreatedastextandusingamemberfunctiongettoreadinputIngeneral,usetheextractionoperatormethodwhenprocessingnumericdata,TheprogramofDisplay6.8Readseverycharacteroffilecad.datandcopiesittofilecplusad.datexceptthateveryCischangedtoC+incplusad.datPreserveslinebreaksincad.datgetisusedforinputastheextractionoperatorwouldskiplinebreaksgetisusedtopreservespacesaswellUseseoftotestforendoffile,Slide6-80,Display
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 厨房功能室活动方案策划
- 吉林彩钢板安装施工方案
- 定制家具施工方案怎么写
- 浙江活动方案策划制作团队
- 建筑方案设计深度标准要求
- 公司活动策划创意分享方案
- 2025法律职业资格考试真题含完整答案详解(典优)
- 【高考模拟】2026届高考全国一卷英语综合模拟强化练习 (含解析)
- 我们应该怎样学习议论文关于学习方法的话题(13篇)
- 2024医学检验(师)考前冲刺练习附答案详解AB卷
- 遥感原理与应用 课件 第7、8章 定量遥感、遥感技术的应用
- 干部履历表模板
- 患者隐私保护培训课件
- 《SolidWorks 2024项目教程》高职全套教学课件
- 儿童肥胖的危害和预防-培训课件
- 加气站气瓶充装质量保证体系手册2024版
- 2025版宝鸡市房地产评估服务合同范本(含保密条款)2篇
- 《集成电路技术导论》课件
- 医疗机构药品管理法
- 弹幕游戏主播培训
- 医疗器械经营质量管理制度和工作程序目录
评论
0/150
提交评论