840 likes | 981 Views
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. Streams. A stream is a sequence of bytes. Bytes are moved from memory to devices, and vice versa.
E N D
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
Streams • A stream is a sequence of bytes. • Bytes are moved from memory to devices, and vice versa. • The stream I/O facilities convert typed objects into sequences of characters, and vice versa.
iostream Library Header Files • <iostream.h> basic stream input and output operations • <iomanip.h> formatted I/O with parametrized stream manipulators • <fstream.h> file processing • <strstream.h>//<strstrea.h> in VC++ formatting with character arrays
ios istream ostream iostream fstream I/O Class Hierarchy
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); ...
Output of User-Defined Types #include <iostream.h> 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; } };
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<<!!!
The put Member Function #include <iostream.h> 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 Result:? 26; 2.5 XXY
The Input Stream cin #include <iostream.h> 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
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&); ...
The istream::get functions class istream : public virtual ios { ... int get(); istream& get(char& c); istream& get(char* p, int n, char=‘\n’); ... };
get() with no arguments • returns the next input character • reads white space • returns EOF when end of stream is reached
get() with no arguments • #include <iostream.h> • int main() • {char name[80]; • char ch = '\0'; • int i = 0; • cout << "Enter your name: "; • while(1) • { ch = cin.get(); • if( ch == '\n') break; • cout.put(ch); • name[i++] = ch; • } • name[i] = '\0'; • cout <<'\n'<< name<<'\n'; • return 0; • }//ex10-4.cpp
get(char&) with one argument • reads the next input character into the character argument • reads white space • returns false when end of stream is reached • returns an istream reference
Using get(char&) to Copy #include <iostream.h> void main() { char ch; while( cin.get(ch) && (ch != '\n')) cout.put(ch); }//ex10-5.cpp It is a test. It is a test. Result:
The 3-argument istream::get() • istream & get (char * buf, int len, char delim = ‘\n’) • reads at most (len-1) characters • stores input into a vector of characters(buf) • stores the null character at the end • stops reading when delimiter is encountered • delimiter will be the next character to read
#include <iostream.h> 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
ignore • istream istream::ignore(int n=1, int delim=EOF); • skips the specified number of character the default is 1, or until the delimiter is reached, the default is EOF.
getline() #include <iostream.h> 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 Result: Enter a name: John Smith John Smith
Error Detection • #include <iostream.h> • void main() • {int i; • float r; • long n; • cin >> i >> r>>n; • cout<<"i = "<<i<<'\n' • <<"r = "<<r<<'\n' • <<"n = "<<n<<'\n' • <<"cin.good()= "<<cin.good()<<'\n'; • }//ex10-6-3.cpp
The io-state bits class ios { //... public: enum io_state { goodbit = 0, eofbit = 1, failbit = 2, badbit = 4 }; ... };
The rdstate() Member Function • returns the state of a stream as a set of io-state bits: int s = cin.rdstate();
Examining the State • if( s & ios::goodbit ) // last operation on cin succeeded if( s & ios::badbit ) // characters from cin possibly lost • if( s & ios::failbit ) // some formatting error if( s & ios::eofbit ) // reached the end of file
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
Input of User-Defined Types void main() { rational r; cin >> r; cout << "r = " << r << '\n' ; } //ex10-6-4.cpp
Unformatted I/O functions • read • istream& istream::read(char* ptr, int n); • reads into a character array the number of characters specified by the second argument n. • write • ostream& ostream::write(const char*, int ); • outputs from the character array the number of bytes specified by its second argument. • gcount • int istream::gcount(); • returns the number of characters read by the last input operation
Example Result: #include <iostream.h> 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
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
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); ... };
The fill Member function • Allows us to specify the fill character cout.fill(‘#’); (remains in effect until changed)
Manipulators • allows formatting operations to be inserted directly in the list of input or output operations. #include <iostream.h> #include <iostream.h> void main() { int n, m; cin >>dec >>n; cin >>hex >>m; cout<<dec << n << "; "<<m<< endl; }//ex10-7.cpp Result: 12 12 12; 18
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
Example #include <iostream.h> #include <iomanip.h> 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
User-Defined Manipulators • manipulator to produce a tab ostream& tab(ostream& os) { return os << ‘\t’ ; } • produce an \n and a flush ostream& ENDL(ostream& s) { return s << ‘\n’ << flush ; }
Example #include <iostream.h> #include <iomanip.h> 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
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)
Example #include <iostream.h> #include <iomanip.h> 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
Other Manipulators smanip<int> setfill(int);//set the filling ‘c’ smanip<int> setprecision(int); //set the spaces to display smanip<int> setw(int); //set the spaces to display the following ...
ios Manipulator (with argument) #include <iostream.h> #include <iomanip.h> 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
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
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. }; // ... };
Flags • 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);
setf(long) and unsetf(long) • setf(long) sets the options specified by its argument, without changing any of the other options. • unsetf(long) unsets the options specified by its argument.