Presentation is loading. Please wait.

Presentation is loading. Please wait.

The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.

Similar presentations


Presentation on theme: "The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams."— Presentation transcript:

1 The C++ Programming Language Streams

2 Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams

3 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';

4 Notes u 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);

5 Stream: Output (2) Built-in Types class ostream : public virtual ios { public: //... u ostream& operator<<(const char*); // string u ostream& operator<<(char); u //... u ostream& operator<<(long); u ostream& operator<<(double);  ostream& operator<<(const void*); // pointer };

6 main() { int i =0; int* p = new int(1); cout << "local " << &i << ", free store " << p << '\n'; }

7 Notes u cerr is pre-initiated as an object of ostream u cerr << "x = " << x; => (cerr.operator<<("x = ")).operator<<(x); u Possible result: local 0x7ffead0, free store 0x500c

8 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) << ")"; }

9 Notes main() { complex x(1, 2); cout << "x = " << x << '\n'; } produced x = (1,2)

10 Stream: Input (1) Examples int a; char b[10]; cin >> a >> b;

11 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); //... };

12 Notes u istream::get(char &)} reads a single character into its argument main() { char c; while ( cin.get(c) ) cout << c; }

13 u 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'); }

14 Stream: Input (3) Stream States u 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};

15 Notes u good(): next input operation might succeed u eof(): end of file u The difference between the states fail() and bad() is subtle and only really interesting to implementers of input operations

16 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 }

17 else { s.putback(c); s >> re; } if (s) a = complex(re,im); return s; }

18 Notes u An input operation can be defined for a user-defined type exactly as an output operation was, but for an inputoperation it is essential that the second argument is of reference type

19 Stream: Formatting (1) Typing of Streams u The tie() function is used to set up and break connections between an istream and an ostream (cf. t cin.tie(cout)) u When an ostream is tied to an istream the ostream is flushed whenever an input operation is attempted on the istream u is.tie(0) unties the stream is from the stream it was tied to, if any. u A call without an argument, tie(), returnsthe current value

20 Notes cin.tie(cout); cout << "Password: "; cout << "Password: "; cout.flush(); cin >> s; cin >> s;

21 Stream: Formatting (2) Output Fields u 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 << ')';

22 u The padding or filler character can be specified by the fill() function cout.width(4); cout.fill('#'); cout << '(' << "ab" << ')'; // output: (##ab) u Default: as many characters as needed

23 u A call of width() affects only the immediate following output operations cout.width(4); cout.fill('#'); cout << '(' << 12 << ')', (" << '(' 12 << ")\n"; // output is (##12),(12)

24 Notes

25 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

26 // 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 }; //... };

27 Format State (cont'd) u An ios has a format state that is controlled bythe flags() and setf() functions u 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

28 Notes

29 Integer Output u 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

30 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)

31 Notes u Internal adjustment places fill characters betweenthe sign and the value

32 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

33 Notes u Note that values are rounded rather than just truncated

34 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;

35 ostream& flush(ostream&); typedef ostream& (*Omanip) (ostream&); ostream& operator > ws >> x;

36 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); } };

37 ostream& _set_precision(ostream&,int); Omanip_int setprecision(int i) { return Omanip_int(&_set_precision,i); } cout << setprecision(4) << angle;

38 Manipulators (3) Standard I/O Manipulators ios& oct(ios&); //used octal notation ios& dec(ios&); //used decimal notation ios& hex(ios&); //used hexadecimal notation ostream& endl(ostream&); //add '\n' and flush ostream& ends(ostream&); //add '\0' and flush ostream& flush(ostream&); // flush stream istream& ws(istream&);// eat whitespace

39 SMANIP setbase(int b); SMANIP setfill(int f); SMANIP setprecision(int p); SMANIP setw(int w); SMANIP resetiosflags(long b); SMANIP setiosflags(long b); cout << 1234 << ' ' << hex << 1234 << ' ' << oct << 1234 << endl;// 1234 4d2 2322 cout << setw(4) << setfill('#') << '(' << 12 << ")\n"; // (##12)

40 Files & Streams u File Stream: fstream,ifstream, ofstream ofstream mystream("test.txt",ios::out|ios::nocreat); fstream dictionary("my.dic",ios::in|ios::out); mystream.close ();

41 u 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;


Download ppt "The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams."

Similar presentations


Ads by Google