已阅读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年大学生素质教育活动合同
- 2025年保安员证考试题库及答案
- 2025年科创板股票投资知识题库及答案
- 2025年反假币知识培训应知应会考试题库含答案
- 初中心理健康浙教版八年级上册(边玉芳)第八课 网络是把双刃剑教案设计
- 人工智能识别财报舞弊的实证研究
- 大单元教学设计 八年级上册 第三单元 资产阶级民主革命与中华民国的建立
- 2025年临床执业医师考试技能操作要求试题及答案
- 《丰收中国年》教学设计-2025-2026学年中职基础课-全一册-高教版(2023)-(音乐)-69
- 儿科进修汇报讲课件
- 房屋安全培训课件
- 垃圾清运合同 垃圾清运承包方案(九篇)
- 劳务合同的免责协议书模板
- 2025年住房城乡建设领域现场专业人员“三新”技术网络培训考试题库及答案(共130题)
- 中考体适能训练协议书
- 学前教育信息化2025年技术创新报告:人工智能在教育领域的应用前景与挑战
- 国有林场合作协议书
- 长江生态环境的恢复与保护 - 课件
- 招标代理廉政合同协议书
- 广东省深圳市某中学2025届高三年级下册3月一模 历史试题(含解析)
评论
0/150
提交评论