下载

1下载券

加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 The C++ IOStreams Library

The C++ IOStreams Library.pdf

The C++ IOStreams Library

wonderko
2010-03-30 0人阅读 举报 0 0 0 暂无简介

简介:本文档为《The C++ IOStreams Librarypdf》,可适用于IT/计算机领域

TheCIOStreamsLibraryIntroductionThesimplestwaytoviewaprogramisasadevicefortransforminginputintooutputPrograminputoutputAprogramisuselessunlesswehaveawayofgettinginformationintotheprogram,andawayofgettingitoutagainInputforaprogramcanbefrommanysourceseg:•UserInputPrompttheuserforsomeinformationandhavethementeritatthecommandlineorinsometextfieldofaGUI•TheCommandLineReadvariousoptionsargumentsfromthecommandlinewhentheprogramisinvoked•EnvironmentVraiablesMostoperatingsystemsshellsallowtheusertoset”environmentvariables”egMOZILLAHOME=usrlocalappsnetscapethoughthepreciseformvariesfromOStoOSandshelltoshellAprogramcangainaccesstotheseenvironmentvariablesthroughplatformdependentlibraryfunctions•FilesReadinformationfromaconfigurationfile,importadocumentfortheusertoedit,exhibitanimageforausertomanipulateetc•SensorsTakereadingsdirectlyfromelectronicsensors•OtherProgramsTakeyourinputfromtheoutputofanotherprogram,requestanotherprogram(stillrunning)tosendsomedataetcAnyoneprogrammayuseanyorallofthesesourcesOnceinsideinputcanbebroadlyclassifiedaseither:•Configurationinformationthataffectsthestateoftheprogramandhowitbehaves•Datatobeprocessed,eitherautomaticallyorinteractivelywithauserAllprogramscanbeconsideredtobeofthisformifyousufficientlycomplicateyourdescriptionoftheinputandoutputHoweverothermodelswith,say,feedbackloopswouldbeamorecomfortablefittointeractiveGUIprogramsOutputfromaprogramcangotomanyplaces:•TheUserDisplaysomeinformationonthecommandlineorinaGUImessageboxetcThissortofoutputisephemeralunlesstheusertakessomeactiontocaptureit•FilesStoresomeinformationinafileThismaycontaintextualoutput(egsomeprogramcode)orbinaryoutput(egaJPEGimage)•ActuatorsSendsignalstosomeequipmentthatcausesittoundertakesomeaction(egswitchingoffanuclearreactor)•OtherProgramsConnectyouroutputtotheinputofanotherprogram,sendsomedata(whilstyouarestillactive)toanotherprogrametcTheCIOStreamsLibrary,partoftheCStandardLibrary,providesauniformwayofhandlinginputfrom(andoutputto)anyoftheabovesources(includinghardwaredevices)exceptforcommandlineargumentsandenvironmentvariablesSuchargumentsaredeliveredtotheprogrambytheoperatingsystemviatheargvparameterofthemainfunction:intmain(intargc,char**argv){argccontainsthenumberofargumentsargvisanarrayofcharacterarraysholdingtheactualarguments}ThelibraryconsistsofasetofclasstemplateswhichcanbespecialisedbytheusertohandleanysortofinputdataTheycomewithreadymadespecialisationstohandlesimplecharacterbasedinputandoutputeithertoandfromtheconsoleortoandfromnormalfilesThesenotesgiveanoverviewofthefacilitiesoftheIOStreamslibraryAnothersetofnoteswilldiscusscommandlineargumenthandlingThesenotesaremoderatelylongforasetofnotesbuttheyareshortincomparisontothefacilitiesprovidedthemainreferenceIusedwhilstwritingthem,Josuttis,devotesachapterofpagestothetopic!BasicUsageYouwillalreadyhavemademuchuseofcoutandcinstreamsfordoingsimpleinputandoutputtoandfromtheconsole(commandline)Forexamplethefollowingprogram(thecodeisinthefileexamplesexcc)promptstheusertoentersomevaluesandthenprintsoutthevaluesentered#include<iostream>Thismighthavetobeiostreamh#include<string>intmain(intargc,char**argv){intxdoublegcharcstringstrcout<<"Enteraninteger:"cin>>xcout<<"Enterarealnumber:"cin>>gcout<<"Enteracharacter:"cin>>ccout<<"Enterastring:"cin>>strcout<<"Youentered:"<<endlcout<<"theinteger"<<x<<endlcout<<"therealnumber"<<g<<endlcout<<"thecharacter’"<<c<<"’"<<endlcout<<"thestring""<<str<<"""<<endl}Notehowtheinsertionoperator<<andtheextractionoperator>>areoverloadedtohandlemanydifferenttypesThewriterofanewclasscanalsooverloadtheseoperatorssothatobjectsofthatclasscanbewrittenandreadinthesamewayasthebuiltintypesNotehoweverthattheseoperatorsdonotdovalidationiftheuserenterssomethingunexpectedatthepromptyoucanendupwithgarbagevaluesforthevariableAlsotheinputstreamisnotflushedafterareadoperationThusifatthefirstpromptEnteraninteger:theuserinfactenteredtykjvohitheretheprogramwouldcontinuewithoutwaitingforuserinput:Enterarealnumber:Enteracharacter:Enterastring:Youentered:theintegertherealnumberthecharacter’t’thestring"ykjvo"WhilstiftheuserhadenteredyhiyouwouldgetEnterarealnumber:Enteracharacter:Enterastring:Youentered:theintegertherealnumberthecharacter’thestring""ThebehaviouroftheextractionoperatoristoskipleadingwhitespacethenreadcharactersuntilacharacternotbelongingtothestringrepresentationofthedatatypebeinginputisencounteredAnyremainingcharactersareleftinthecinstreamtobereadbythenextuseoftheextractionoperatorYoucanforcetheprogramtoskipreadingtherestofalineafteranextractionoperationbyusingtheignorememberfunctionofthecinstreamobjectThisfunctionhasanumberofformsbuttheonetousehereis(thisisnotquitetherealsignaturebutitshowstheintentmoreclearly)ignore(intcount,chardelim)Thebehaviouristoreadanddiscarduptocountcharactersuntilthecharacterdelimisread(thischaracterisalsodiscarded)Thuscinignore(,’n’)woulddiscarduptoacharactersoruntilanendoflinecharacterwasfound(whichevercamefirst)Youcanusefunctionslikethisandothersifyouwanttodovalidatedinput(thatisyoudon’ttrusttheusertoentercorrectdata)ButabetterwaytoproceedisprobablytowriteaGUIwithdataentryfieldswhichcanbemoreeasilycheckedforvalidityUseextractionfromcinforquickanddirtyprogramsorforformattedinputfromsomepreviouslyconstructedfileattachedtothecinstream(seelater)TheotheraspectoftheaboveexamplesisthatwhenreadingastringwiththeextractionoperatoryoucannotincludewhitespaceinthestringThatisifyouwantedtoreadthestring”Hello,World!”youwouldhavetoreaditintwobits(Hello,andWorld!)andthenputitbacktogether!Ifyouwanttoreadstringswithembeddedspacesyoushouldusethe(global)functiongetlinevoidgetline(istreamin,stringstr,chardelim=’n’)providedbythestringlibraryThisfunctionignoresleadingspacesandthenreadsallcharactersuntilthelinedelimiterorendoffileisreachedThelinedelimiterisextractedfromthestreambutnotappendedtothestringThedefaultlinedelimitercharacteristhenewlinecharacter’n’butyoucanpassyourownasanoptionalargument(inwhichcasethenewlinecharacterisnotspecialandmaybeappendedtothestringbeingreadin)Thusabetterwaytoreadthestringintheaboveprogramwouldbecinignore(,’n’)Toflushanynewlinecharactersetcseewhathappensifyoudon’tusethisfunctioncout<<"Enterastring:"getline(cin,str)BehindtheScenesTheIOStreamsLibraryisbasedontheconceptofa”stream”Astreamcanrepresentafile,theconsole,blocksofmemoryorhardwaredevicesThelibraryprovidesacommonsetofinterfaces(functions)forhandlingstreamsThegeneralpictureisasinFigureIODeviceObjectStateBufferTranslatorSTREAM>><<ExtractorInserterFigure:StreamStructureTheuserofastreamobjectrarelyhastobeconcernedwiththebufferandtranslationcomponentswhichhandleconversionofindividualbitsfromtheIOdeviceintothestructureddataofanobject(ofeitherabuiltintypesuchasanintegerorauserdefinedtype)HowevertheuserwillneedtokeepawatchonthestatecomponentwhichnoteswhetherornotanIOoperationhassucceededorfailedThelibraryisbuiltusingafairlycomplicatedsetofclasstemplateswiththerelationshipsdepictedinFigureFigure:TheClassStructureoftheIOStreamLibraryEachofthebasicxxxxclassesinthediagramisaclasstemplate,egtemplate<classcharT>classbasicios{}andthestandardstreamclassesareobtainedbyaseriesoftypedef’s:typedefbasicistream<char>istreamtypedefbasicostream<char>ostreamtypedefbasiciostream<char>iostreamtypedefbasicistringstream<char>istringstreamtypedefbasicostringstream<char>ostringstreamtypedefbasicstringstream<char>stringstreamtypedefbasicifstream<char>ifstreamtypedefbasicofstream<char>ofstreamtypedefbasicfstream<char>fstreamTheiostreamheaderfileprovidesthestandardstreams:istreamcinostreamcoutostreamcerrostreamclogNoteTheabovedescriptionisbasedonthecurrentstandardNotallcompilerslibrarieshavecaughtupwiththestandardandsomearestillusinganoldstyleiostreamlibrarywhichwasnotbuiltaccordingtotheaboveschemeHoweverthenewlibrary(above)wasdesignedsothattheinstantiatedclasseshavethesameinterfacesastheoldstyleandworkinthesamewayThemainexceptionisthatoldstylestringstreamsareistrstream,ostrstreamandstrstreamratherthanistringstreametcCurrentlytheGNUCStandardlibraryisinastateoftransitionItstillusesstrstreametcanddoesnotbasethestreamclassesonbasicxxxxtemplateclassesbutdoesprovidemostofthenewstyleiostreamfunctionsandmanipulators(asof,butisfurtherbehind)TheStateofStreamsEachstreammaintainsastatethatidentifieswhetheranIOoperationwassuccessfulornot,and,ifnot,thereasonforthefailureThestateofastreamisdeterminedbythesettingsofanumberofflagsTheseflagsareconstantsoftypeiostate(amemberofthebaseclassiosbase)Theflagsare:•goodbit:Ifthisissetalltheotherflagsarecleared•eofbit:Ifthisissetthenendoffilewasencountered•failbit:IfthisissetthentheoperationwasnotprocessedcorrectlybutthestreamisgenerallyOKForexamplethisflagwouldbesetifanintegerwastobereadbutthenextcharacterisaletter•badbit:ThisissetifthestreamhassomehowbecomecorruptedorifdataislostThecurrentstateoftheflagscanbedeterminedbycallingvariousbooleanreturningmemberfunctionsthatallstreamclassespossess•good()–ReturnstrueifthestreamisOK(goodbitisset)•eof()–Returnstrueifendoffilewasencountered(eofbitisset)•fail()–Returnstrueifanerrorhasoccurred(failbitorbadbitisset)•bad()–Returnstrueifafatalerrorhasoccurred(badbitisset)Streamsalsopossessthefollowingmoregeneralflagmanipulationfunctions•Youcanaccessalltheflagsusingios::iostaterdstate()asinthefollowingexample(tobefoundinexamplesrdstateexcc)#include<iostream>intmain(){intxcout<<"Enteraninteger:"cin>>xThestateofthestreamcanbegottenwithrdstateios::iostateflags=cinrdstate()WecantestforwhichbitsaresetasfollowsNotetheuseofthebitwiseoperatorif(flagsios::failbit)cout<<"failbitset"<<endlelsecout<<"failbitnotset"<<endlif(flagsios::badbit)cout<<"badbitset"<<endlelsecout<<"badbitnotset"<<endlif(flagsios::eofbit)cout<<"eofbitset"<<endlelsecout<<"eofbitnotset"<<endlIt’susuallyeasiertotestthebitsdirectly:if(cingood())cout<<"Streamstateisgood"<<endlelsecout<<"Streamstateisnotgood"<<endlif(cinfail())cout<<"Areyousureyouenteredaninteger"<<endlelsecout<<"Youentered:"<<x<<endl}•Youcanclearall,orselected,flagsbyusingvoidclear(ios::iostateflags=ios::goodbit)Thuscinclear()willclearallflagswhilstcinclear(ios::failbit)willclearjustthefailbitflagManipulatingYourStreamAttheendofmanyoutputstatementsamanipulatoriswritten:cout<<"Youentered:"<<x<<endlThemostimportantmanipulatorsprovidedbytheIOStreamlibraryareasfollows•endl–usedwithaostream,outputanewlineandflushthebuffer•ends–usedwithaostream,outputacharacter()•flush–usedwithaostream,flushestheoutputbuffer•ws–usedwithaistream,readsanddiscardswhitespaceFormattingYourStreamWhenoutputtingvaluestotheconsoleorafile(inotherwordsonaistream)youoftenwanttoformatthemindomeway,egprintafloatingpointnumberinafieldofwidthwiththreedecimalplacesetcTheeasiestwaytodothisistouseoneofthemanyformattingmanipulatorsandflagsForexamplethefollowingprogramgeneratesrandomnumbersbetweenand(notincluding)andwritesthemouttoafileonetoalinewithdecimalplaces,aleadingzeroandadecimalpoint(Thecodecanbefoundinexamplesrndnumscc)#include<iostream>Mayneedtobe<iostreamh>#include<iomanip>Mayneedtobe<iomaniph>#include<cstdlib>Requiredforrand()mayneedtobe<stdlibh>#include<ctime>Foraccesstotimefunctions(mayneedtobe<timeh>)doublegenerateRandNum(){intintRN=rand()Eachtimerand()iscalleditgeneratesarandomlychosenintegerbetweenandRANDMAXThisisnotthewaytogenerate"good"randomnumbersbetweenandbut’twilldoforaquickanddirtyhackreturndouble(intRN)RANDMAX}intmain(){doublern=Usesystemtimetoseedrandomnumbergeneratorwithdifferentnumbereachtimeprogramisrunsrand(time())Standardsaysthatfixedshouldbeamanipulatorsothatwecouldwritecout<<fixedButgdoesnotcurrentlysupportthiscoutsetf(ios::fixed)cout<<setprecision()for(inti=i<i){rn=generateRandNum()cout<<rn<<endl}}Thetwolinesthataredoingtheformattingintheaboveare:coutsetf(ios::fixed)cout<<setprecision()Hereios::fixedisaflagthatsaysthefixedpointnotationshouldbeusedandprecision(val)isamanipulatorthatsetsvalastheprecisionoffloatingpointvaluesAsitisamanipulatorwithargumentyouhavetoinclude<iomanip>Notehowthefunctionsetf(amemberfunctionofallstreams)canbeusedtosetaflagThefunctionforclearingaflagisunsetfThustoturnofffixedpointnotationyouwoulddo:coutunsetf(ios::fixed)TherearemanipulatorsandflagswhichcontrolmanydifferentaspectsofinputandoutputofcharactervaluesThefollowingsectionsandtablessummarisetheavailablemanipulators,theflagstheyset,whethertheyaretobeusedforinputoroutputandwhethertheyarecurrentlyavailablewithgTheselistsandexplanationsarenotexhaustive(eveniftheyseemexhausting)BooleanValuesManipulatorAffectedFlagEffectInputOutputg()boolalphaios::boolalphaThiscontrolshowboolvariablesareprintedIftheflagissetthenbooleanvaluesareprintedastrueorfalseIftheflagisnotsetthentheyprintasorThismanipulatorsetstheflagInputOutputNeithernoboolalphaios::boolalphaThenoboolalphamanipulatorunsetstheboolalphaflagInputOutputNeitherAsyoucanseetheGNUgIOStreamLibrarydoesnotyetprovidethisfeatureIfyouwanttoprinttrueorfalseforthevaluesofabooleanvariableyoucandosomethinglike:cout<<(b"true":"false")<<endlFieldWidths,FillCharactersandOutputAdjustmentManipulatorAffectedFlagEffectInputOutputg()setw(val)NoneSetsthefieldwidthtovalThisisaminimumvalue(iftheoutputvalueiswiderthanthesetwidththenthewidthsettingisignored)ThesettingonlyaffectsthenextformattedoutputInputOutputManipulatorsetfill(c)NoneSetsthecharacterctobethefillcharacterOutputManipulatorleftios::leftThemanipulatorsetstheflagIftheflagissetthenthevalueisoutputleftadjustedinthefieldOutputFlagrightios::rightThemanipulatorsetstheflagIftheflagissetthenthevalueisrightadjustedinthefieldOutputFlaginternalios::internalThemanipulatorsetstheflagIftheflagissetthenthevalueisprintedwiththesignleftadjustedandthevaluerightadjustedOutputFlagNotethatafteranyformattedoutputoperationthedefaultfieldwidthisrestoredThefillcharacterandtheadjustmentsettingremainunchangeduntilresetPositiveSignandUppercaseLettersManipulatorAffectedFlagEffectInputOutputg()showposios::showposThemanipulatorsetstheshowposflagIfthisflagissetthenapositivesign()willbeprintedinfrontofanypositivenumber(whenusingdecimalnotation)OutputFlagnoshowposios::showposThismanipulatorclearstheshowposflagOutputFlaguppercaseios::uppercaseThemanipulatorsetstheflagIftheflagissetthenintegersusinghexadecimalnotation,orfloatingpointnumbersusingscientificnotation,useuppercaseforanylettersappearinginthemOutputFlagnouppercaseios::uppercaseThemanipulatorclearstheflagOutputFlagNumberBaseManipulatorAffectedFlagEffectInputOutputg()decios::decThisflagsetsthenumberbaseforintegernumberprintingandreadingtodecimalInputOutputBothhexios::hexManipulatorsetsthehexflagWhichcausesinputandoutputofintegerstousehexadecimalnotationInputOutputBothoctios::octManipulatorsetstheoctflagWhichcausesinputandoutputofintegerstouseoctalnotationInputOutputBothIfnoneoftheseflagsissetthenadecimalbaseisused,ifmorethanoneflagissetthenadecimalbaseisusedDuringinputifnoflagissetthenthebaseisdeterminedbytheleadingcharactersAnumberstartingwithxorXisreadasahexadecimalnumber,whilstifitstartswithaleadingzeroitisreadasanoctalnumberUsingthemanipulatorsiseasierthanusingtheflagsToreadwritebinarynumbersusethebitsetclassfromtheStandardTemplateLibraryFloatingPointRepresentationManipulatorAffectedFlagEffectInputOutputg()fixedios::fixedThemanipulatorsetstheflagIfflagissetusefixedpointdecimalnotationforfloatingpointnumbersOutputFlagscientificios::scientificThemanipulatorsetstheflagIftheflagissetthenusescientificnotationforfloatingpointnumbersOutputFlagshowpointios::showpointThemanipulatorsetstheflagIftheflagissetalwayswriteadecimalOutputFlagnoshowpointios::showpointThemanipulatorclearstheflagOutputFlagsetprecision(val)NoneSetstheprecisionoffloatingpointprintingtovalOutputManipulatorAsyoucanseetherearenomanipulatorsforclearingthefixedorscientificflagsUseunsetfforthistaskOutputstreamsalsohaveaprecision()memberfunctionwhichreturnsthecurrentprecisionMiscellaneousManipulatorAffectedFlagEffectInputOutputg()endlNoneOutputanewlinecharacterandflushthestreamOutputManipulatorendsNoneOutputacharacterOutputManipulatorflushNoneFlushastreamOutputManipulatorStreamMember

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/15

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利