View
45
Download
1
Category
Preview:
DESCRIPTION
The C++ Programming Language. Streams. Contents. Output Stream Input Stream Formatting Manipulators Files & Streams. Stream: Output (1). cout
Citation preview
The C++ Programming Language
Streams
Contents
Output Stream Input Stream Formatting Manipulators Files & Streams
Stream: Output (1)
cout << "a*b+c=" << a*b+c << '\n'; cout << "a^b|c=" << (a^b|c) << '\n'; cout << "a<<b=" << (a<<b) << '\n';
Notes
operator << is not new one, just overridden operator output stream
printf("a<<=%d\n", a<<b); printf("a^b|c=%d\n", a^b|c); printf("a*b+c=%f\n", a*b+c);
Stream: Output (2) Built-in Types
class ostream : public virtual ios { public: // ... ostream& operator<<(const char*); // string ostream& operator<<(char); // ... ostream& operator<<(long); ostream& operator<<(double); ostream& operator<<(const void*); // pointe
r };
main() { int i =0; int* p = new int(1); cout << "local " << &i << ", free store " << p << '\n'; }
Notes
cerr is pre-initiated as an object of ostream
cerr << "x = " << x; => (cerr.operator<<("x = ")).opera
tor<<(x);
Possible result: local 0x7ffead0, free store 0x500c
Stream: Output (3) User-defined Types
class complex{ double re, im; public: complex(double r = 0, double i = 0) { re=r, im=i; } friend double real(complex& a) {return a.re; } friend double imag(complex& a) {return a.im; } friend complex operator+(complex, complex); friend complex operator-(complex, complex); friend complex operator*(complex, complex); friend complex operator/(complex, complex); //...}; ostream& operator<<(ostream&s, complex z) { return s << "(" << real(z) << "," << image(z) << ")"; }
Notes
main() { complex x(1, 2); cout << "x = " << x << '\n'; }
produced x = (1,2)
Stream: Input (1) Examples
int a; char b[10];
cin >> a >> b;
Stream: Input (2) Built-in Types
class istream : public virtual ios { // ... public: istream& operator>>(char*); // string istream& operator>>(char&); // character istream& operator>>(short&); istream& operator>>(int&); istream& operator>>(long&); istream& operator>>(float&); istream& operator>>(double&); istream& get(char& c); istream& get(char* p, int n, char ='\n'); istream& putback(char& c); // ... };
Notes
istream::get(char &)} reads a single character into its argument main() { char c; while ( cin.get(c) ) cout << c; }
istream::get(char* p, int n, char ch ='\n') read at most n characters into where 'p' points to until the character read is same to ch.
void f() { char buf[100]; cin.get(buf, 100, '\n'); }
Stream: Input (3) Stream States
Every stream has a state associated with it class ios { // ... public: enum io_state { goodbit =0, eofbit =1, failbit =2, badbit =4, }; int eof() const; // end of file seen int fail() const; // next operation will fail int bad() const; // stream corrupted int good() const; // next operation might succeed};
Notes
good(): next input operation might succeed eof(): end of file The difference between the states fail() and
bad() is subtle and only really interesting to implementers of input operations
Stream: Input (3) User-defined Types
istream& operator>>(istream&s, complex&a) { double re =0, im = 0; char c = 0;
s >> c; if (c == '(') { s >> re >> c; if (c == ',') s >> im >> c; if (c != ')') s.clear(ios::badbit); // set state }
else { s.putback(c); s >> re; } if (s) a = complex(re,im); return s; }
Notes
An input operation can be defined for a user-defined type exactly as an output operation was, but for an input operation it is essential that the second argument is of reference type
Stream: Formatting (1) Typing of Streams
The tie() function is used to set up and break connections between an istream and an ostream (cf. t cin.tie(cout))
When an ostream is tied to an istream the ostream is flushed whenever an input operation is attempted on the istream
is.tie(0) unties the stream is from the stream it was tied to, if any.
A call without an argument , tie(), returns the current value
Notes
cin.tie(cout); cout << "Password: "; cout << "Password: "; cout.flush(); cin >> s; cin >> s;
Stream: Formatting (2) Output Fields
The width() function specifies the minimum number of characters to be used for the next numeric or string output operation cout.width(4) cout << '(' << 12 << ')';
The padding or filler character can be specified by the fill() function
cout.width(4); cout.fill('#'); cout << '(' << "ab" << ')'; // output: (##ab)
Default: as many characters as needed
A call of width() affects only the immediate following output operations
cout.width(4); cout.fill('#'); cout << '(' << 12 << ')', (" << '(' 12 << ")\n"; // output is (##12),(12)
Notes
Format State
class ios { public: // flags for controlling format: enum { skipw =01, // skip whitespace on input
// field adjustment: left =02, // padding after value right =04, // padding before value internal=010, // padding between sign and value
// integer base: octal =020, // octal dec =040, // decimal hex =0100, // hexadecimal showbase=0200, // show integer base showpoint=0400, // print tailing zeros uppercase=01000, // 'E', 'X' rather than 'e', 'x' showpos =02000, // explicit '+' for positive ints
//floating point notation scientific=04000, // .dddddd Edd fixed =010000, // dddd.dd
// flush output: unitbuf =020000, // after each output operation stdio =040000, // after each character };
// ... };
Format State (cont'd) An ios has a format state that is controlled by
the flags() and setf() functions The flags() function returns old option set.
const int my_ioflag = ios::left|ios::oct|ios::showpoint|ios::fixed;
old_flag = cout.flags(my_ioflag);
cout.setf(ios::showpos); // explicit '+' for positive int
NotesNotes
Integer Output
C++ provides a version of setf() that takes a second “pseudo argument'' indicating which kind of option we want to set in addition to the new value
cout.setf(ios::oct,ios::basefield); // octal cout << 1234; // output: 2322 cout.setf(ios::hex,ios::basefield); //hexadecimal cout << 1234; // output: 4d2 cout.setf(ios::showbase); cout << 1234; // 0x4d2
Field Adjustment
cout.width(4); cout << '(' << -12 << ")\n"; // output: ( -12) cout.width(4); cout.setf(ios::left, ios::adjustfield); cout << '(' << -12 << ")\n"; // output: (-12 )
cout.width(4); cout.setf(ios::internal, ios::adjustfield); cout << '(' << -12 << ")\n"; // output: (- 12)
NotesNotes
Internal adjustment places fill characters between the sign and the value
Floating-Point Output cout << 1234.56789 << '\n'; // 1234.57
cout.setf(ios::scientific,ios::floatfield); cout << 1234.56789 << '\n'; // 1.234568e+03
cout.setf(ios::fixed,ios::floatfield); cout << 1234.56789 << '\n'; // 1234.567890
cout.precision(8); cout << 1234.56789 << '\n'; // 1234.5679
cout.precision(4); cout << 1234.56789 << '\n'; // 1235
NotesNotes
Note that values are rounded rather than just truncated
Manipulators (1) Manipulators with No Arguments
cout << x; cout.flush(); cout << y;
class Flushtype { }; ostream& operator<<(ostream& os, Flushtype s) { return flush(os); } Flushtype FLUSH; cout << x << FLUSH << y << FLUSH;
ostream& flush(ostream&); typedef ostream& (*Omanip) (ostream&); ostream& operator<<(ostream& os, Omanip f) { return f(os); } cout << x << flush << y << flush;
class ostream: public virtual ios { // ... public: ostream& operator<<(ostream&, ostream& (*)(ostream&)); // ... }; istream& ws(istream& is) {return is.eatwhite(); } cin >> ws >> x;
Manipulators (2) Manipulators with Arguments
class Omanip_int { int i; ostream& (*f)(ostream&,int); public: Omanip_int(ostream& (*ff)(ostream&,int), int ii) : f(ff), i(ii) { } friend ostream& operator<<(ostream& os, Omanip_int& m) { return f(os,i); } };
ostream& _set_precision(ostream&,int); Omanip_int setprecision(int i) { return Omanip_int(&_set_precision,i); }
cout << setprecision(4) << angle;
Manipulators (3) Standard I/O Manipulators
ios& oct(ios&); //used octal notationios& dec(ios&); //used decimal notationios& hex(ios&); //used hexadecimal notation
ostream& endl(ostream&); //add '\n' and flushostream& ends(ostream&); //add '\0' and flushostream& flush(ostream&); // flush stream
istream& ws(istream&); // eat whitespace
SMANIP<int> setbase(int b);SMANIP<int> setfill(int f);
SMANIP<int> setprecision(int p);SMANIP<int> setw(int w);
SMANIP<long> resetiosflags(long b);SMANIP<long> setiosflags(long b);
cout << 1234 << ' ' << hex << 1234 << ' ' << oct << 1234 << endl; // 1234 4d2 2322
cout << setw(4) << setfill('#') << '(' << 12 << ")\n";
// (##12)
Files & Streams
File Stream: fstream,ifstream, ofstream
ofstream mystream("test.txt",ios::out|ios::nocreat); fstream dictionary("my.dic",ios::in|ios::out);
mystream.close();
String Stream char* p = "ABCDEFGHIJKLMN"; char* q = new char[max_size]; char c;
istrstream ist(p,strlen(p)); ostrstream ost(q,max_size);
while (ist>>c) ost << c;
Recommended