版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C++ProgrammingCHAPTER12THEC++INPUT/OUTPUTCLASSHIERARCHY1
12.1Overview
12.2TheHigh-LevelInput/OutputClasses
12.3Manipulators
12.4TheFileInput/OutputClasses
12.5TheCharacterStreamInput/OutputClasses212.1OverviewInputandoutputfacilitiesarenotpartofC++languagebutinsteadoffurnishedthroughaclasslibrary.InC++inputandoutput,acentralobjectisthestream,whichisasequenceofbytes.Thereisacommonbaseclassfortwoderivedstreamclassedbasic_istream,aninputstreamclass,andbasic_ostream,anoutputstreamclass.312.1OverviewThestandardinput/outputhierarchios_basebase_iosbasic_istreambasic_ostreambasic_ifstreambasic_istringstreambasic_iostreambasic_ostringstreambasic_ofstreambasic_stringstreambasic_fstream412.1OverviewSeveralinput/outputheadersanddescribestheirpurpose.HeaderiosfwdiostreamiosstreambufistreamostreamiostreamiomanipsstreamfstreamPartialDescriptionContainsforwarddeclarationsDeclarescin,cout,etc.Declaresios_baseandbasic_iosDeclaresbasic_streambufDeclaresbasic_istreamDeclaresbasic_ostreamDeclaresbasic_istreamandbasic_ostreamDeclaresparameterizedmanipulatorsDeclaresbasic_stringbufandthestringstreamclassesDeclaresbasic_filebufandthefstreamclasses512.2TheHigh-LevelInput/OutputClassesInC++,weusetheclassesbasic_istream,basic_ostream,andbasic_iostreamtogetahigh-levelinterfacetoinputandoutput.HeaderPartialDescriptioniostreamDeclaresbasic_istreamandbasic_iostreamostreamDeclaresbasic_ostreamistreamDeclaresbasic_istream612.2TheHigh-LevelInput/OutputClassesbasic_istreambasic_istreamcin>>valcinreadsthestream,withoutwhitespace,andsaveittotheval.Example:inta;charc;charca[20];cin>>a>>c>>ca;712.2TheHigh-LevelInput/OutputClassesbasic_istreamExample:#include<iostream.h>voidmain(){Input:"5c3.14159helloworld!"intn;charch;cin>>ch;floatpi;cin>>pi;charstr[20];cout<<"n="<<n<<endl;cout<<"ch="<<ch<<endl;cout<<"pi="<<pi<<endl;cout<<"string="<<str<<endl;cin>>n;Output:n=5ch=cpi=3.14159string=hellocin>>str;8}12.2TheHigh-LevelInput/OutputClassesbasic_istream
istream&operator>>(signedchar);istream&operator>>(unsignedchar);istream&operator>>(short);istream&operator>>(unsignedshort);istream&operator>>(int);istream&operator>>(unsignedint);istream&operator>>(long);istream&operator>>(unsignedlong);istream&operator>>(float);istream&operator>>(double);istream&operator>>(longdouble);OperatorOverloaded912.2TheHigh-LevelInput/OutputClassesbasic_istreamMethodsA)get();Whenget()isinvoked,thenextcharacterinthestream,whitespaceornot,isreturned.Example:intc;while((c=cin.get())!=EOF)cout<<c;1012.2TheHigh-LevelInput/OutputClassesbasic_istreamB)getline(char_type*b,streamsizes,char_typed);b:anarray,intowhichtowritecharacters:anintegervaluethatboundsthenumberofcharactersd:anend-of-linemarker1112.2TheHigh-LevelInput/OutputClassesbasic_istreamMethodgetlinereadscharactersuntilit1.2.3.Reachesend-of-fileEncountersanend-of-linemarkerStoress-1characters12Example:#include<iostream>#include<limits>usingnamespacestd;voidmain(void){Input:Beijing,ChinaShanghai,ChinaOutput:City:BeijingCountry:ChinaCity:ShanghaiCountry:Chinacharcity[80];charcountry[80];inti;for(i=0;i<2;i++){cin.getline(city,80,',');cin.get(country,80,'\n');cout<<"City:"<<city<<"Country:"<<country<<endl;cin.clear();cin.ignore(numeric_limits<streamsize>::max(),'\n');}13}12.2TheHigh-LevelInput/OutputClassesbasic_istreamC)read(char_type*a,streamsizen);Methodreadreadscharactersandstorestheminthearrayauntilncharactersarereadorend-of-fileoccurs.1412.2TheHigh-LevelInput/OutputClassesbasic_ostreambasic_ostreamcout<<valcoutputsthestream,inval,tothescreen.Example:cout<<“Hello:”<<123<<endl;1512.2TheHigh-LevelInput/OutputClassesbasic_ostreamExample:#include<iostream.h>voidmain(){floatpi=3.14159;cout<<"pi=";cout<<pi;cout<<endl;Output:pi=3.14159}1612.2TheHigh-LevelInput/OutputClassesbasic_ostream
ostream&operator<<(signedchar);ostream&operator<<(unsignedchar);ostream&operator<<(short);ostream&operator<<(unsignedshort);ostream&operator<<(int);ostream&operator<<(unsignedint);ostream&operator<<(long);ostream&operator<<(unsignedlong);ostream&operator<<(float);ostream&operator<<(double);ostream&operator<<(longdouble);OperatorOverloaded1712.2TheHigh-LevelInput/OutputClassesbasic_ostreamMethodsA)put(char_type);Methodputwritesthecharacterpassedtotheoutputstream.Example:cout.put(c);1812.2TheHigh-LevelInput/OutputClassesbasic_ostreamB)write(constchar_type*a,streamsizem);Methodwritewritesmcharactersfromthearrayatotheoutputstream.1912.2TheHigh-LevelInput/OutputClassesbasic_ostreamExample:#include<iostream.h>#include<string.h>voidmain(){char*pc="thisisatest!";cout.put('A');cout.put('\n');cout.write(pc,strlen(pc));Output:Athisisatest!}2012.2TheHigh-LevelInput/OutputClassesbasic_iostreambasic_iostreamClassbasic_iostreamispubliclyinheritedfrombothbasic_istreamandbasic_ostream.2112.2TheHigh-LevelInput/OutputClassesbasic_iostreamExample:classComplex{public:Complex(){real=0.0;imag=0.0;}Complex(doubler){real=r;imag=0.0;}Complex(doubler,doublei){real=r;imag=i;}Complexoperator+(constComplex&c);Complexoperator-(constComplex&c);Complexoperator*(constComplex&c);Complexoperator/(constComplex&c);friendostream&operator<<(ostream&Out,Complex&x);friendistream&operator>>(istream&In,Complex&x);protected:doublereal,imag;22};12.2TheHigh-LevelInput/OutputClassesbasic_iostreamostream&operator<<(ostream&Out,Complex&x){Out<<x.real<<"+"<<x.imag<<"i"<<endl;returnOut;}istream&operator>>(istream&In,Complex&x){In>>x.real>>x.imag;returnIn;}//……2312.2TheHigh-LevelInput/OutputClassesbasic_iostreamvoidmain(){Complexa(1,2),b(3,4),c;c=a+b;cout<<c;}Output:4+6i2412.3ManipulatorsAmanipulatorsisafunctionthateitherdirectlyorindirectlymodifiesastream.HeaderPartialDescriptioniomanipDeclaresparameterizedmanipulators2512.3ManipulatorsSeveralmanipulatorswithargumentsarepredefined.ManipulatorActsOnPurposesetBase(intn)basic_ostreamSetintegerbaseton(0meansdefault)SetfillcharactertocSetprecisiontonSetfieldwidthtonSetspecifiedformatbitsClearspecifiedformatbitssetfill(char_typec)setprecision(intn)setw(intn)setiosflags(mask)resetiosflags(mask)basic_ostreambasic_ostreambasic_ostreamios_baseios_base2612.3Manipulators
setBaseExample:cout<<setbase(8)<<9<<endl;Output:112712.3Manipulators
Example:#include<iostream>#include<iomanip>usingnamespacestd;voidmain(){setwOutput:Zoot1.23Jimmy35.36Al653.7Stan4358.24doublevalues[]={1.23,35.36,653.7,4358.24};char*names[]={"Zoot","Jimmy","Al","Stan"};for(inti=0;i<4;i++)cout<<setw(6)<<names[i]6106characters<<setw(10)<<values[i]<<endl;28}12.3Manipulators
Example:#include<iostream>#include<iomanip>usingnamespacestd;voidmain(){setfillFillwith‘*’doublevalues[]={1.23,35.36,653.7,4358.24};for(inti=0;i<4;i++){Output:******1.23*****35.36*****653.7***4358.24cout.width(10);cout<<setfill(‘*’)<<values[i]<<'\n';}}2912.3Manipulators
Example:#include<iostream>#include<iomanip>usingnamespacestd;voidmain(){setiosflagsandrsetiosflagsOutput:Zoot1.23Jimmy35.36Al653.7Stan4358.24doublevalues[]={1.23,35.36,653.7,4358.24};char*names[]={"Zoot","Jimmy","Al","Stan"};for(inti=0;i<4;i++)cout<<setiosflags(ios::left)//flushleft<<setw(6)<<names[i]<<resetiosflags(ios::left)<<setw(10)<<values[i]<<endl;//removeflushleft30}setprecisionExample:#include<iostream>#include<iomanip>usingnamespacestd;voidmain(){Output:ZootJimmyAlStan1.2e+0003.5e+0016.5e+0024.4e+003doublevalues[]={1.23,35.36,653.7,4358.24};char*names[]={"Zoot","Jimmy","Al","Stan"};cout<<setiosflags(ios::scientific);for(inti=0;i<4;i++)Precision1cout<<setiosflags(ios::left)<<setw(6)<<names[i]<<resetiosflags(ios::left)<<setw(10)<<setprecision(1)<<values[i]<<endl;}3112.4TheFileInput/OutputClassesTheclassesbasic_filebuf,basic_ofstream,basic_ifstreamandbasic_fstreamaredeclaredinfstream.HeaderPartialDescriptionfstreamDeclaresbasic_filebufandthefstreamclassesTherearetwokindsoffiles:textandbinarytext.3212.4TheFileInput/OutputClassesbasic_ofstream
basic_ofstream(constchar*filename,basic_ofstreamios_base::openmodemode=io_base::out);Theconstructorisusedtoassociateabasic_ofstreamobjectwiththefilefilename,whichisopenedinmodemode.Thetypeopenmodeisabitmasktype.Thedefaultmodeisoutput.3312.4TheFileInput/OutputClassesbasic_ofstreamA)ofstreamoutfile("outfile",iosmode);B)ofstreammyFile;myFile.open("filename",iosmode);C)ofstream*pmyFile=newofstream;pmyFile->open("filename",iosmode);3412.4TheFileInput/OutputClassesbasic_ofstreamExample:#include"fstream.h"#include"iostream.h"voidmain(){Outputfilecharbuf[80];ofstreamout("out.txt");while(cin.getline(buf,80,''))Getdata{cout<<buf<<endl;out<<buf<<endl;}35}12.4TheFileInput/OutputClassesbasic_ifstreambasic_ifstreambasic_ifstream(constchar*filename,ios_base::openmodemode=io_base::in);Theconstructorisusedtoassociateabasic_ifstreamobjectwiththefilefilename,whichisopenedinmodemode.Thedefaultmodeisinput.3612.4TheFileInput/OutputClassesbasic_ifstreamA)ifstreamoutfile("infile",iosmode);B)ifstreammyFile;myFile.open("filename",iosmode);C)ifstream*pmyFile=newifstream;pmyFile->open("filename",iosmode);3712.4TheFileInput/OutputClassesbasic_ifstreamExample:ifstreamfin(“data.in”);if(!fin)cerr<<”Can’topendata.in\n”;Example:ifstreamfin;fin.open(“data.in”);3812.4TheFileInput/OutputClassesbasic_ifstreamExample:#include"fstream.h"#include"iostream.h"voidmain(){Inputfileintline=1;charbuf[80];ifstreamin("in.txt");ofstreamout("out.txt");Outputfilewhile(in.getline(buf,80))Readdata{cout<<line++<<":"<<buf<<endl;out<<buf<<endl;}39}12.4TheFileInput/OutputClassesbasic_fstreambasic_fstreambasic_fstream(constchar*filename,ios_base::openmodemode=ios_base::in|ios_base::out);Theconstructorisusedtoassociateabasic_fstreamobjectwiththefilefilename,whichisopenedinmodemode.Thedefaultmodeisinputandoutput.4012.4TheFileInput/OutputClassesbasic_fstreamA)fstreamoutfile("file",iosmode);B)fstreammyFile;myFile.open("filename",iosmode);C)fstream*pmyFile=newfstream;pmyFile->open("filename",iosmode);4112.4TheFileInput/OutputClassesbasic_fstreamExample:fstreamfinout(“data.txt”);Inthiscasethefiledata.txtisforbothinputandoutput.42#include<fstream>//forfilestreams#include<iostream>usingnamespacestd;constintMAX=100;//sizeofbufferintbuff[MAX];//bufferforintegersintmain(){//fillbufferwithdataWritedatafor(intj=0;j<MAX;j++)buff[j]=j;//(0,1,2,...)//createoutputstreamofstreamos("edata.txt",ios::binary);//writetoitos.write((char*)buff,MAX*sizeof(int));os.close();//mustcloseit43for(j=0;j<MAX;j++)//erasebufferbuff[j]=0;//createinputstreamifstreamis("edata.txt",ios::binary);//readfromitis.read((char*)(buff),MAX*sizeof(int));for(j=0;j<MAX;j++)//checkdataif(buff[j]!=j){cerr<<"Dataisincorrect\n";return1;}cout<<"Dataiscorrect\n";return0;}Readdata44Output:data.txt?????????????????????????!"#$%&'()*+,-/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\_`abc.]^4512.4TheFileInput/OutputClassesMethodsMethodsbasic_ofstream:1open2close3tellp:Getsthevalueforthestream’sputpointer.4612.4TheFileInput/OutputClassesbasic_fstream4seekp(streampospos);5seekp(streamoffoff,ios::seek_dirdir);pos:Thenewpositionvalue;streamposisatypedefequivalenttolong.off:Thenewoffsetvalue;streamoffisatypedefequivalenttolong.dir:Theseekdirectionspecifiedbytheenumeratedtypeios::seek_dir,withvaluesincluding:ios::begSeekfromthebeginningofthestream.ios::curSeekfromthecurrentpositioninthestream.ios::endSeekfromtheendofthestream.4712.4TheFileInput/OutputClassesbasic_fstreambasic_ifstream:1open2close3get4getline5read6tellg:Getsthevalueforthestream’sgetpointer.4812.4TheFileInput/OutputClassesbasic_fstream7seekg(streampospos)8seekg(streamoffoff,ios::seek_dirdir)pos:Thenewpositionvalue;streamposisatypedefequivalenttolong.off:Thenewoffsetvalue;streamoffisatypedefequivalenttolong.dir:Theseekdirection.Mustbeoneofthefollowingenumerators:ios::begSeekfromthebeginningofthestream.ios::curSeekfromthecurrentpositioninthestream.ios::endSeekfromtheendofthestream.49Example:1#include<fstream>//forfilestreams#include<iostream>usingnamespacestd;classperson//classofpersons{protected:charname[80];//person'snameintage;//person'sagepublic:voidgetData()//getperson'sdata{cout<<"\nEntername:";cin>>name;cout<<"Enterage:";cin>>age;}voidshowData(void)//displayperson'sdata{cout<<"\nName:"<<name;cout<<"\nAge:"<<age;}};50intmain(){charch;personpers;//createpersonobjectfstreamfile;//createinput/outputfilefile.open("GROUP.DAT",ios::app|ios::out|ios::in|ios::binary);do//datafromusertofile{reinterpret_cast<char*>(&pers)?cout<<"\nEnterperson'sdata:";pers.getData();//getoneperson'sdatafile.write(reinterpret_cast<char*>(&pers),sizeof(pers));//writetofilecout<<"Enteranotherperson(y/n)?";cin>>ch;}while(ch=='y');//quiton'n'51file.seekg(0);//resettostartoffile//readfirstpersonfile.read(reinterpret_cast<char*>(&pers),sizeof(pers));while(!file.eof())//quitonEOF{cout<<"\nPerson:";//displaypersonpers.showData();//readanotherpersonfile.read(reinterpret_cast<char*>(&pers),sizeof(pers));}cout<<endl;return0;}52Example:2intmain(){personpers;//createpersonobjectifstreaminfile;//createinputfileinfile.open("GROUP.DAT",ios::in|ios::binary);//openfileinfile.seekg(0,ios::end);//goto0bytesfromendintendposition=infile.tellg();//findwhereweareintn=endposition/sizeof(person);//numberofpersonscout<<"\nThereare"<<n<<"personsinfile";53cout<<"\nEnterpersonnumber:";cin>>n;intposition=(n-1)*sizeof(person);//numbertimessizeinfile.seekg(position);//bytesfromstart//readonepersoninfile.read(reinterpret_cast<char*>(&pers),sizeof(pers));pers.showData();//displaythepersoncout<<endl;return0;}5412.5T
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 离心式冷水机组技术规格书
- 江西省九江市六校2024-2025学年九年级上学期期中联考化学试题(含答案)
- 第六章《世界的发展差异》 2024-2025学年湘教版七年级上册地理单元测试卷(含解析)
- 拨浪鼓玩具产品供应链分析
- 对流式烤箱产品供应链分析
- 压茶砖机市场需求与消费特点分析
- 双向触发极管产业深度调研及未来发展现状趋势
- 人教版英语八年级上册 期末常见题型能力提升练习
- 湖北省武汉市洪山区鲁巷实验小学2024~2025学年二年级上学期期中数学试题
- 医用白朊制剂产业运行及前景预测报告
- 海利普SJ系列变频器使用说明书
- 接地变使用说明书(共11页)
- 产品外观检验标准(全球通用)
- 博雅计划试题
- 钻孔灌注桩验孔记录表
- 偏差管理控制程序
- 如何高效进行初中信息技术学业水平考试复习
- 浅埋暗挖施工方法大全图文PPT课件
- 托卡马克装置原理2[1]
- “模拟法庭”在高中法律教学中的应用与探究
- 毕业设计说明书螺旋精确称重给料机设计
评论
0/150
提交评论