《C++程序设计教学课件:CHAPTER 12 THE C++ INPUT OUTPUT CLASS HIERARCHY》由会员分享,可在线阅读,更多相关《C++程序设计教学课件:CHAPTER 12 THE C++ INPUT OUTPUT CLASS HIERARCHY(62页珍藏版)》请在金锄头文库上搜索。
1、C+ Programming CHAPTER 12 THE C+ INPUT/OUTPUT CLASS HIERARCHY1l12.1 Overviewl12.2 The High-Level Input/Output Classes l12.3 Manipulatorsl12.4 The File Input/Output Classesl12.5 The Character Stream Input/Output Classes212.1 OverviewInput and output facilities are not part of C+ language but instead
2、of furnished through a class library.In C+ input and output, a central object is the stream, which is a sequence of bytes. There is a common base class for two derived stream classed basic_istream, an input stream class, and basic_ostream, an output stream class.312.1 OverviewThe standard input/outp
3、ut hierarchios_basebase_iosbasic_istreambasic_ostreambasic_istringstream basic_iostreambasic_ostringstreambasic_stringstreambasic_fstreambasic_ifstreambasic_ofstream412.1 OverviewSeveral input/output headers and describes their purpose.HeaderPartial DescriptioniosfwdContains forward declarationsiost
4、reamDeclares cin, cout, etc.iosDeclares ios_base and basic_iosstreambufDeclares basic_streambufistreamDeclares basic_istream ostreamDeclares basic_ostreamiostreamDeclares basic_istream and basic_ostreamiomanipDeclares parameterized manipulatorssstreamDeclares basic_stringbuf and the stringstream cla
5、ssesfstreamDeclares basic_filebuf and the fstream classes512.2 The High-Level Input/Output ClassesIn C+, we use the classes basic_istream, basic_ostream, and basic_iostream to get a high-level interface to input and output.HeaderPartial DescriptioniostreamDeclares basic_istream and basic_iostreamost
6、reamDeclares basic_ostreamistreamDeclares basic_istream 612.2 The High-Level Input/Output Classesbasic_istreambasic_istreamcinvalcin reads the stream, without white space, and save it to the val.Example:int a; char c; char ca20;cinacca;712.2 The High-Level Input/Output Classesbasic_istreamExample:#i
7、nclude void main()int n; cinn;char ch; cinch;float pi; cinpi;char str20;cinstr;coutn=nendl;coutch=chendl;coutpi=piendl;coutstring=str ( signed char);istream & operator (unsigned char);istream & operator (short);istream & operator (unsigned short);istream & operator (int);istream & operator (unsigned
8、 int);istream & operator (long);istream & operator (unsigned long);istream & operator (float);istream & operator (double);istream & operator (long double);912.2 The High-Level Input/Output Classesbasic_istreamMethodsA) get( );When get() is invoked, the next character in the stream, white space or no
9、t, is returned.Example:int c;while( ( c=cin.get( ) )!=EOF ) coutc;1012.2 The High-Level Input/Output Classesbasic_istreamB) getline( char_type* b, streamsize s, char_type d );b: an array, into which to write characters: an integer value that bounds the number of charactersd: an end-of-line marker111
10、2.2 The High-Level Input/Output Classesbasic_istreamMethod getline reads characters until it1.Reaches end-of-file2.Encounters an end-of-line marker3.Stores s-1 characters 12Example:#include#includeusingnamespacestd;voidmain(void)charcity80;charcountry80;inti;for(i=0;i2;i+)cin.getline(city,80,);cin.g
11、et(country,80,n);coutCity:cityCountry:countryendl;cin.clear();cin.ignore(numeric_limits:max(),n);Input:Beijing,ChinaShanghai,ChinaOutput:City:BeijingCountry:ChinaCity:ShanghaiCountry:China1312.2 The High-Level Input/Output Classesbasic_istreamC) read( char_type* a, streamsize n);Method read reads ch
12、aracters and stores them in the array a until n characters are read or end-of-file occurs.1412.2 The High-Level Input/Output Classesbasic_ostreambasic_ostreamcoutvalcout puts the stream, in val, to the screen.Example:cout“Hello:”123endl;1512.2 The High-Level Input/Output Classesbasic_ostreamExample:
13、#include void main()float pi=3.14159;coutpi=;coutpi;coutendl;Output:pi=3.141591612.2 The High-Level Input/Output Classesbasic_ostreamOperator Overloadedostream & operator ( signed char);ostream & operator (unsigned char);ostream & operator (short);ostream & operator (unsigned short);ostream & operat
14、or (int);ostream & operator (unsigned int);ostream & operator (long);ostream & operator (unsigned long);ostream & operator (float);ostream & operator (double);ostream & operator (long double);1712.2 The High-Level Input/Output Classesbasic_ostreamMethodsA) put( char_type );Method put writes the char
15、acter passed to the output stream.Example:cout.put( c );1812.2 The High-Level Input/Output Classesbasic_ostreamB) write( const char_type* a, streamsize m); Method write writes m characters from the array a to the output stream.1912.2 The High-Level Input/Output Classesbasic_ostreamExample:#include #
16、includevoid main( )char* pc=this is a test!;cout.put(A);cout.put(n);cout.write(pc,strlen(pc); Output:Athisisatest!2012.2 The High-Level Input/Output Classesbasic_iostreambasic_iostreamClass basic_iostream is publicly inherited from both basic_istream and basic_ostream.2112.2 The High-Level Input/Out
17、put Classesbasic_iostreamExample:class Complexpublic:Complex( )real=0.0;imag=0.0;Complex(double r)real=r;imag=0.0;Complex(double r, double i)real=r;imag=i;Complex operator + (const Complex& c);Complex operator - (const Complex& c);Complex operator * (const Complex& c);Complex operator / (const Compl
18、ex& c);friend ostream& operator (istream& In, Complex& x);protected:double real, imag;2212.2 The High-Level Input/Output Classesbasic_iostreamostream& operator(ostream& Out, Complex& x)Outx.real+x.imagi(istream& In, Complex& x)Inx.realx.imag;return In;/2312.2 The High-Level Input/Output Classesbasic
19、_iostreamvoid main()Complex a(1,2),b(3,4),c;c=a+b;coutc;Output:4+6i2412.3 ManipulatorsA manipulators is a function that either directly or indirectly modifies a stream.HeaderPartial DescriptioniomanipDeclares parameterized manipulators2512.3 ManipulatorsSeveral manipulators with arguments are predef
20、ined. ManipulatorActs OnPurposesetBase( int n )basic_ostreamSet integer base to n(0 means default)setfill(char_type c)basic_ostreamSet fill character to csetprecision( int n )basic_ostreamSet precision to nsetw( int n )basic_ostreamSet field width to nsetiosflags( mask )ios_baseSet specified format
21、bitsresetiosflags( mask ) ios_baseClear specified format bits2612.3 ManipulatorssetBaseExample:coutsetbase(8) 9endl;Output:112712.3 ManipulatorssetwExample:#include #include using namespace std;void main() double values =1.23,35.36,653.7,4358.24;char *names =Zoot,Jimmy,Al,Stan;for(int i=0;i4;i+)cout
22、setw(6)namesi setw(10)valuesi endl; Output:Output: ZootZoot 1.23 1.23 Jimmy 35.36 Jimmy 35.36 Al 653.7 Al 653.7 Stan 4358.24 Stan 4358.246 106 characters2812.3 ManipulatorssetfillExample:#include #include using namespace std; void main() double values =1.23,35.36,653.7,4358.24; for(int i=0; i4; i+)
23、cout.width(10); coutsetfill(*)valuesin; Output:*1.23*35.36*653.7*4358.24Fill with *2912.3 Manipulatorssetiosflags and rsetiosflagsExample:#include #include using namespace std; void main() double values=1.23,35.36,653.7,4358.24; char *names=Zoot,Jimmy,Al,Stan; for(int i=0;i4;i+) coutsetiosflags(ios:
24、left) setw(6)namesi resetiosflags(ios:left) setw(10)valuesi endl;/ flush left/ remove flush leftOutput:Zoot1.23Jimmy35.36Al653.7Stan4358.2430setprecisionExample:#include #include using namespace std; void main() double values=1.23,35.36,653.7,4358.24; char *names=Zoot,Jimmy,Al,Stan; coutsetiosflags(
25、ios:scientific); for(int i=0;i4;i+) coutsetiosflags(ios:left) setw(6)namesi resetiosflags(ios:left) setw(10)setprecision(1) valuesiopen(filename,iosmode); 3412.4 The File Input/Output Classesbasic_ofstreamExample:#include fstream.h#include iostream.hvoid main()char buf80;ofstream out(out.txt);while
26、(cin.getline(buf,80, ) coutbufendl;outbufopen(filename,iosmode); 3712.4 The File Input/Output Classesbasic_ifstreamExample:ifstream fin( “data.in” );if( !fin )cerr”Cant open data.inn”;Example:ifstream fin;fin.open( “data.in” );3812.4 The File Input/Output Classesbasic_ifstreamExample:#include fstrea
27、m.h #include iostream.hvoid main()int line=1;char buf80;ifstream in(in.txt);ofstream out(out.txt);while (in.getline(buf,80) coutline+:bufendl;outbufopen(filename,iosmode); 4112.4 The File Input/Output Classesbasic_fstreamExample:fstream finout( “data.txt” );In this case the file data.txt is for both
28、 input and output.42#include /for file streams#include using namespace std;const int MAX = 100; /size of bufferint buffMAX; /buffer for integersint main() /fill buffer with data for(int j=0; jMAX; j+) buffj = j; /(0, 1, 2, .) /create output stream ofstream os(edata.txt, ios:binary); /write to it os.
29、write( (char*)buff, MAX*sizeof(int) ); os.close(); /must close itWritedata43 for(j=0; jMAX; j+) /erase buffer buffj = 0; /create input stream ifstream is(edata.txt, ios:binary); /read from it is.read(char*)(buff), MAX*sizeof(int) ); for(j=0; jMAX; j+) /check data if( buffj != j ) cerr Data is incorr
30、ectn; return 1; cout Data is correctn; return 0; Readdata44Output:data.txt!#$%&()*+,-./0123456789:;?ABCDEFGHIJKLMNOPQRSTUVWXYZ_abc4512.4 The File Input/Output ClassesMethodsMethodsbasic_ofstream:1 open2 close3 tellp: Gets the value for the streams put pointer.4612.4 The File Input/Output Classesbasi
31、c_fstream4 seekp( streampos pos );5 seekp( streamoff off, ios:seek_dir dir );pos:The new position value; streampos is a typedef equivalent to long.off: The new offset value; streamoff is a typedef equivalent to long.dir: The seek direction specified by the enumerated type ios: seek_dir, with values
32、including: ios: beg Seek from the beginning of the stream. ios: cur Seek from the current position in the stream. ios: end Seek from the end of the stream.4712.4 The File Input/Output Classesbasic_fstreambasic_ifstream:1 open2 close3 get4 getline5 read6 tellg: Gets the value for the streams get poin
33、ter.4812.4 The File Input/Output Classesbasic_fstream7 seekg(streampos pos)8 seekg(streamoff off, ios:seek_dir dir) pos: The new position value; streampos is a typedef equivalent to long. off: The new offset value; streamoff is a typedef equivalent to long. dir: The seek direction. Must be one of th
34、e following enumerators: ios:beg Seek from the beginning of the stream. ios:cur Seek from the current position in the stream. ios:end Seek from the end of the stream.49Example:1#include /for file streams#include using namespace std;class person /class of personsprotected:char name80; /persons namein
35、t age; /persons agepublic:void getData() /get persons datacout name;cout age;void showData(void) /display persons datacout n Name: name;cout n Age: age;50int main() char ch; person pers; /create person object fstream file; /create input/output file file.open(GROUP.DAT, ios:app | ios:out | ios:in | i
36、os:binary ); do /data from user to file cout nEnter persons data:; pers.getData(); /get one persons data file.write( reinterpret_cast(&pers), sizeof(pers) ); /write to file cout ch; while(ch=y); /quit on nreinterpret_cast(&pers)?51 file.seekg(0); /reset to start of file /read first person file.read(
37、 reinterpret_cast(&pers), sizeof(pers) ); while( !file.eof() ) /quit on EOF cout nPerson:; /display person pers.showData(); /read another person file.read( reinterpret_cast(&pers), sizeof(pers) ); cout endl; return 0;52Example:2int main() person pers; /create person object ifstream infile; /create i
38、nput file infile.open(GROUP.DAT, ios:in | ios:binary); /open file infile.seekg(0, ios:end); /go to 0 bytes from end int endposition = infile.tellg(); /find where we are int n = endposition / sizeof(person); /number of persons cout nThere are n persons in file;53 cout n; int position = (n-1) * sizeof
39、(person); /number times size infile.seekg(position); /bytes from start /read one person infile.read( reinterpret_cast(&pers), sizeof(pers) ); pers.showData(); /display the person cout endl; return 0;5412.5 The Character Stream Input/Output ClassesThe classes basic_stringbuf, basic_ostringstream, bas
40、ic_istringstream and basic_stringstream are declared in sstream.HeaderPartial DescriptionsstreamDeclares basic_stringbuf and the stringstream classes5512.5 The Character Stream Input/Output Classesbasic_ostringstreambasic_ostringstreamThe class basic_ostringstream is used to write characters to an i
41、nternal buffer that can be copied to a basic_string.basic_ostringstream( iso_base:openmode =ios_base:out );5612.5 The Character Stream Input/Output Classesbasic_ostringstreamExample:string name=monica;ostringstream sout( name );Example:ostringstream sout;soutmonica123;coutsout.str()x;coutx=valendl;O
42、utput:x=37.8055912.5 The Character Stream Input/Output Classesbasic_stringstreambasic_stringstreamThe class basic_stringstream is used to read and write an internal buffer that can be copied to a basic_string.basic_stringstream(ios_base:openmode =io_base:in | ios_base:out );60SummarizeManipulatorsbasic_istream, basic_ostream,basic_iostreambasic_ofstream, basic_ifstream, basic_fstreambasic_ostringstream, basic_istringstream, basic_stringstream61Exercise:Read from file “in.txt”, and write it into file “D:out.dat” in binary. For every line in “D:out.dat”, please add a mask(0,1,2,). 62