Download presentation
Presentation is loading. Please wait.
2
1 Input/Output Stream Lesson #10 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek
3
2 Streams u A stream is a sequence of bytes. u Bytes are moved from memory to devices, and vice versa. u The stream I/O facilities convert typed objects into sequences of characters, and vice versa.
4
3 iostream Library Header Files u basic stream input and output operations u formatted I/O with parametrized stream manipulators u file processing u // in VC++ formatting with character arrays
5
4 I/O Class Hierarchy ios istreamostream iostream fstream
6
5 Output of Built-in Types class ostream : public virtual ios {... public: ostream& operator<<(const char*); ostream& operator<<(char); ostream& operator<<(short); ostream& operator<<(int); ostream& operator<<(long); ostream& operator<<(double);...
7
6 Output of User-Defined Types #include class rational { int num, den; public: rational(int n=0, int d=1) { num=n; den = d; } int get_num() { return num; } int get_den() { return den; } };
8
7 Output of User-Defined Types ostream& operator<<(ostream& os, rational r) {os << '(' << r.get_num() <<',' << r.get_den() <<')'; return os; } void main() {rational r(3, 10); cout << "r = " << r << '\n' ; }//ex10-1.cpp, output: r = (3,10) Overloading the operator<<!!!
9
8 The put Member Function #include void main() {int n = 26; float f = 5.0 / 2.0; cout << n <<"; "<<f<<endl; char c ='X' ; cout.put(c); cout.put(c).put('Y').put('\n') ; }//ex10-2.cpp 26; 2.5 XXY Result:?
10
9 The Input Stream cin #include void main() {int a, b; float r; char ch; cout <<"input two integers, one float and a character: \n"; cin >> a >> b >> r >> ch; cout <<"a= " << a << ", b= " << b << '\n' ; cout <<"r= " << r << ", ch= " << ch << '\n' ; }//ex10-3.cpp
11
10
12
11 Input of Built-in Types class istream : public virtual ios { //... public: istream& operator>>(char *); istream& operator>>(char&); istream& operator>>(short&); istream& operator>>(int&); istream& operator>>(long&); istream& operator>>(float&);...
13
12 The istream::get functions class istream : public virtual ios {... int get(); istream& get(char& c); istream& get(char* p, int n, char=‘\n’);... };
14
13 u returns the next input character u reads white space u returns EOF when end of stream is reached get() with no arguments
15
14 get() with no arguments u #include u int main() u {char name[80]; u char ch = '\0'; u int i = 0; u cout << "Enter your name: "; u while(1) u { ch = cin.get(); u if( ch == '\n') break; u cout.put(ch); u name[i++] = ch; u } u name[i] = '\0'; u cout <<'\n'<< name<<'\n'; u return 0; u }//ex10-4.cpp
16
15
17
16 get(char&) with one argument u reads the next input character into the character argument u reads white space u returns false when end of stream is reached u returns an istream reference
18
17 Using get(char&) to Copy #include void main() {char ch; while( cin.get(ch) && (ch != '\n')) cout.put(ch); }//ex10-5.cpp It is a test. Result:
19
18 The 3-argument istream::get() u istream & get (char * buf, int len, char delim = ‘\n’) u reads at most (len-1) characters u stores input into a vector of characters(buf) u stores the null character at the end u stops reading when delimiter is encountered u delimiter will be the next character to read
20
19 #include main() {char name[30]; while(1) {cout << “Enter a name:”; cin.get(name, 30, ‘\n’); //cin.get(name, 30); if (cin.get(ch) && ch == ‘\n’) break; else { cout << “excess input!”<<endl; cin.ignore(1000, ‘\n’); } cout <<name<<endl; } }//ex10-6.cpp
21
20 u ignore u istream istream::ignore(int n=1, int delim=EOF); u skips the specified number of character the default is 1, or until the delimiter is reached, the default is EOF.
22
21 getline() #include void main() {char name[30], ch; while(1) {cout << "Enter a name:"; cin.getline(name, 30); if (cin.get(ch) && ch == '\n') break; else {cout << "excess input!"<<endl; cin.ignore(100, '\n'); } cout << name<<endl; }//ex10-6-2.cpp Enter a name: John Smith John Smith Result:
23
22 Error Detection u #include u void main() u {int i; u float r; u long n; u cin >> i >> r>>n; u cout<<"i = "<<i<<'\n' u <<"r = "<<r<<'\n' u <<"n = "<<n<<'\n' u <<"cin.good()= "<<cin.good()<<'\n'; u }//ex10-6-3.cpp
24
23
25
24
26
25 The io-state bits class ios { //... public: enum io_state { goodbit = 0, eofbit = 1, failbit = 2, badbit = 4 };... };
27
26 The rdstate() Member Function u returns the state of a stream as a set of io-state bits: int s = cin.rdstate();
28
27 Examining the State u if( s & ios::goodbit ) // last operation on cin succeeded if( s & ios::badbit ) // characters from cin possibly lost u if( s & ios::failbit ) // some formatting error if( s & ios::eofbit ) // reached the end of file
29
28 Input of User-Defined Types istream& operator>>(istream& s, rational & r) {/* allow only input of the form: (n) or (n,d)*/ int n=0, d=1; char c; s >> c; if ( c == '(' ) {s >> n >> c; if (c == ',') s >> d >> c; if ( c == ')') r =rational(n,d); } else s.putback(c); return s; }//add this to ex10-1.cpp => ex10-6-4.cpp
30
29 Input of User-Defined Types void main() {rational r; cin >> r; cout << "r = " << r << '\n' ; } //ex10-6-4.cpp
31
30
32
31 Unformatted I/O functions u read u istream& istream::read(char* ptr, int n); u reads into a character array the number of characters specified by the second argument n. u write u ostream& ostream::write(const char*, int ); u outputs from the character array the number of bytes specified by its second argument. u gcount u int istream::gcount(); u returns the number of characters read by the last input operation
33
32 #include void main() {char v[20]; int n; cin.read( v, 10); n = cin.gcount() ; cout <<n << endl; cout.write( v, n); }//ex10-6-1.cpp 1234567890 10 1234567890 Result: Example
34
33 The Class ios class ios {... public: ostream* tie(ostream* s);//set the stream tied ostream* tie();//get the stream tied long flags(long f);//set the new, return the prev. long flags() const;//return the current flag
35
34 long setf(long setbits, long field);//set flags in a //particular field and return the old long setf(long);//set one or more flags, return the old long unsetf(long);//clear one or more flags, return old int rdstate() const;//get the state of the stream int eof() const;//check reaching the end of the stream int fail() const; int bad() const; int good() const; void clear()(int i=0);... };
36
35 The fill Member function u Allows us to specify the fill character cout.fill(‘#’); (remains in effect until changed)
37
36 Manipulators u allows formatting operations to be inserted directly in the list of input or output operations. #include void main() {int n, m; cin >>dec >>n; cin >>hex >>m; cout<<dec << n << "; "<<m<< endl; }//ex10-7.cpp 12 12; 18 Result:
38
37 Standard Manipulators ios& oct(ios&);//output in octal ios& dec(ios&);//output in decimal ios& hex(ios&);//outpur in hexadecimal ostream& endl(ostream&); //add a ’\n’ and flush ostream& ends(ostream&); //add a ’ ’ and flush ostream& flush(ostream&);// output the buffer istream& ws(istream&);// ignore the space
39
38 Example #include void main() { int j = 200; cout << ".........." << '\n' <<setw(5)<<1<< '\n' <<2 << '\n' <<setw(6)<<3<< '\n' << setfill('*') << setw(10) << j << '\n' << setw(6) << j +1 << endl; } //ex10-8.cpp
40
39 User-Defined Manipulators u manipulator to produce a tab ostream& tab(ostream& os) {return os << ‘\t’ ;} u produce an \n and a flush ostream& ENDL(ostream& s) {return s << ‘\n’ << flush ; }
41
40 Example #include ostream& tab(ostream& os) {return os << '\t';}; ostream& ENDL(ostream& s){return s << ‘\n’ << flush ; } void main() {int A = 65, B = 42; char x[20]; cout <<A << ',' <<oct <<A << ',‘ <<hex <<A << ',' <<B << ',‘ <<dec <<B << ','<<endl; cin >> ws >> x; cout << tab <<"x = "<< tab << x << ENDL; }//ex10-9.cpp
42
41 How Does it Work? class ostream : public virtual ios {//... public: ostream& operator<<(ostream& (*f)(ostream &)) {return (*f)(*this);} //... }; ostream& tab(ostream& os) {return os << '\t';}; ostream& ENDL(ostream& s){return s << ‘\n’ << flush ; } cout <<tab <<ENDL; //… cout.operator<<(tab).operator <<(ENDL) //tab(cout) ENDL(cout)
43
42 Example #include void main() { float x = 123.45; cout.width(8); cout.fill('*'); cout.setf(ios::left, ios::adjustfield); cout <<"x = " << x <<endl; cout.setf(ios::scientific, ios::floatfield); cout << 1234.56789<<endl; cout.precision(7); cout << 1234.56789 <<'\n'; } //ex10-10.cpp
44
43
45
44 Other Manipulators smanip setfill(int);//set the filling ‘c’ smanip setprecision(int); //set the spaces to display smanip setw(int); //set the spaces to display the following...
46
45 ios Manipulator (with argument) #include void main() {int x = 23; float f = 12.345; cout <<setw(6)<<setfill('#')<< hex << x << '\n';//no dot cout << oct << x << '\n'; cin >> oct >> x; cout << dec<<x<<ends; cout <<setprecision(6) << f << '\n'; //effective digits, round up }//ex10-11.cpp
47
46
48
47 Format State class ios { public: enum { skipws=01, //skip white space on input left=02, // padding after value right=04, // padding before value internal=010, //padding between sign/value dec=020, // decimal oct=040, // octal hex=0100, //hexadecimal
49
48 showbase=0200,// show integer base showpoint=0400,// print trailing zeros uppercase=01000,// ‘E’ ‘X’, not ‘e’ ‘x’ showpos=02000,// explicit ‘+’ for integers scientific=04000,//.dddddd Edd fixed=010000,// dddd.dd unitbuf=020000,//flush after each operat. stdio=040000//flush after each char. }; //... };
50
49 Flags u A set of formatting instructions using the function flags(). int options= ios::right | ios::hex | ios::fixed; cout.flags(options );// saving options and setting a new one int old_opt = cout.flags(new_opt); // changing one option without affecting others cout.flags(cout.flags() | ios::showpos ); // restoring old options cout.flags(old_opt);
51
50 setf(long) and unsetf(long) u setf(long) sets the options specified by its argument, without changing any of the other options. u unsetf(long) unsets the options specified by its argument.
52
51 The setf(long, long) Function cout.setf(ios::oct, ios::basefield); cout.setf(ios::dec, ios::basefield); cout.setf(ios::hex, ios::basefield); cout.setf(ios::left, ios::adjustfield); cout.setf(ios::right, ios::adjustfield); cout.setf(ios::internal, ios::adjustfield); cout.setf(ios::scientific, ios::floatfield); cout.setf(ios::fixed, ios::floatfield); cout.setf( 0, ios::floatfield); // default
53
52 The precision() Member Function u specifies the floating point precision u the default is 6 u remains set until next call to precision cout.precision(8);
54
53 Formatting Functions class ios { //... public: int width(int w);//set the width return the prev. one int width() const;//return the current width int precision(int);//set the new, return the old, int precision() const;//return the current char fill(char); //set the new char and returns the prev char fill() const; //return the current fill character … };
55
54 The width Member Function u Allows us to specify the minimum number of characters to be used for the next numeric or string output operations. cout.width(5); u affects only the immediate numeric or string output. u larger values will not be truncated. u smaller values will be padded with the fill characters.
56
55 Example 1 #include void main() {float g = 1.2345678; cout <<g <<'\n'; char oldfill = cout.fill('0'); int oldprecis = cout.precision(4);//four effective digits cout.width(8) cout << g << '\n'; cout.fill(oldfill); cout.precision(oldprecis); cout.width(8); cout<< g << '\n'; }//ex11-12.cpp
57
56
58
57 Example 2 #include void main() { double e = 1.234; float f = 2.1, g = 1212.25; char ch = 'a'; cout.setf(ios::fixed|ios::showpoint); cout <<setfill('*')<<setprecision(4)<<setw(10)<<f<<'\n'; int options= ios::right | ios::hex | ios::fixed, i = 22; cout.flags(options); cout <<setw(6)<<i<<endl; }//ex11-13.cpp
59
58
60
59 Files and Streams class ostream : public virtual ios { //... public: ostream& flush(); ostream& seekp(streampos); ostream& seekp(streamoff, seek_dir); streampos tellp(); //... };
61
60 Seek Direction class ios { //... public: enum seek_dir { beg=0, cur=1, end=2 }; //... };
62
61 Opening an Output File u ofstream of(“data”, ios::out); u in ios::out mode the file is truncated u by default, ofstream implies that the file is opened as “out” mode. u ofstream of(“data”); u Append Mode u ofstream of(“data”, ios::app);
63
62 File Opening Modes u ios::app//Write output to end of file u ios::ate//Move to end of file. Allows //data to be written anywhere u ios::in//Open file for input u ios::out//Open file for output u ios::trunc//erase file contents u ios::nocreate//if file does not exist, the //operation fails u ios::noreplace//if the file exists, the operation //fails
64
63 The open Member function u An ofstream object can be created without opening a specific file: ofstream of; u A file can be attached to an ofstream object: of.open(“data”, ios::out);
65
64 Testing the Success of open u if ( ! of )... true if failbit or badbit are set. u Possible errors: u opening a non-existent file u attempting to read without permission u attempting to write with no disk space
66
65 The void* operator u returns 0 if badbit or failbit has been set: ios::operator void*() const { return fail() ? (void *)0 : (void *) (-1) ; }
67
66 Closing a File u A file is implicitly closed when the ofstream object is destroyed. u We can explicitly close a file by using: of.close();
68
67 Members of istream class istream : public virtual ios { //... public: int peek(); istream& putback(char c); istream& seekg(streampos); istream& seekg(streamoff, seek_dir); streampos tellg(); //... };
69
68 Opening an Input File u By default files are open as “in” mode: ifstream if(“indata”, ios::in); ifstream if(“indata”);
70
69 The open Member Function u An ifstream object may be created without specifying a file: ifstream if; if.open(“indata”, ios::in);
71
70 Repositioning a File Pointer u Reposition pointer at the beginning: if.seekg(0) u Reposition to the nth byte: if.seekg(n); u Position y bytes back from end if.seekg(y, ios::end); u Position at end of file: if.seekg(0, ios::end);
72
71 tellg and tellp u tellg() and tellp() return the current pointer position: long pos = if. tellg();// Gets the value for the //stream's get pointer. long pos = if. tellp();// Gets the value for the stream's put pointer
73
72 Creating an Inventory #include void main() { char name[10]; int quantity; ofstream outf("inventory", ios::out); if( !outf ) { cerr << "Cannot open file\n"; exit(1); } cout << "Enter item name and quantity: " << endl; while( cin >> name >> quantity) outf << name << ' ' << quantity << endl; }//ex10-inventory.cpp ^z to end!!!
74
73
75
74 Read/Print Inventory #include void main() { char name[10]; int quantity; ifstream inf("inventory", ios::in); if( !inf ) { cerr << "Cannot open file\n";exit(1); } while( inf >> name >> quantity) cout << setiosflags(ios::left) << setw(10) << name << setiosflags(ios::right) << setw(7) << quantity << endl; }//ex10-rpinve.cpp
76
75
77
76 Query Inventory #include void main() { char name[10]; int quantity; char item[10]; ifstream inf("inventory", ios::in); if( !inf ) {cerr << "Cannot open file\n"; exit(1); }
78
77 Query Inventory cout << "item name:"; cin >> item; inf >> name >> quantity; while( !inf.eof() ) { if( !strcmp(name, item) ) cout << setiosflags(ios::left) << setw(10) << name << setiosflags(ios::right) << setw(7) << quantity << endl; inf >> name >> quantity; } }//ex10-queryinv.cpp
79
78
80
79 Processing String Streams u Supported by the class istrstream. u Allows: u inputting from character arrays in memory u outputting to character arrays in memory u must include the following header filesin your program: u iostream.h u strstream.h//strstrea.h for VC++
81
80 Types of ostrstream Objects u Dynamic: Allocates space as need. The member function str() is used to fix its size. u Static: The object is initialized with a fixed-size array.
82
81 A Dynamic ostrstream #include void main() {ostrstream s; char* s1 = "Hello, world"; s << s1 << 123 << '\n'; s << "goodbye\n" << ends; char* string = s.str(); cout << string; }//ex10-dyn.cpp Hello, world123 goodbye Result:
83
82 A Static ostrstream u #include u void main() u { const int size=6; u int x=12345; u char buf[size]; u ostrstream s(buf, size, ios::out); u s << "x = " << x << ends; u cout << "buf contains: " << buf << endl; u }//ex10-static.cpp
84
83
85
84 Reading u Readings u Chapter 2 Section 2.5, u Chapter 3 Sections 3.5 - 3.6
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.