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

Slides:



Advertisements
Similar presentations
Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005.
Advertisements

CPS120: Introduction to Computer Science INPUT/OUTPUT.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
I/O Streams as an Introduction to Objects and Classes
 2006 Pearson Education, Inc. All rights reserved Stream Input/Output.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
1 Lecture 6: Input/Output (II) Introduction to Computer Science Spring 2006.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Unformatted and Formatted I/O Operations. 2 Unformatted Input/output is the most basic form of input/output. Unformatted I/O transfers the internal binary.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ Programming Certificate University of Washington Cliff Green
FORMATTED INPUT OUTPUT. Topics to be discussed……………….. Formatted Console I/O operationsFormatted Console I/O operations Defining field width :Width()Defining.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 11 Customizing I/O Bjarne Stroustrup
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Object Oriented Programming in C++ Chapter 11 STL.
Definition Various stream manipulators can be used to specify the kinds of formatting to be performed during stream-I/O operations. Stream manipulators.
C++ Streams Lecture-2.
Output Formatting No, I don't want 6 digits…. Standard Behavior Rules for printing decimals: – No decimal point: prints as 1 – No trailing zeros:
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
CPS120: Introduction to Computer Science Formatted I/O.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11- C++ Stream Input/Output Outline 11.1Introduction 11.2Streams Iostream Library Header.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Student Book Input / Output in C++
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 31 Thanks for Lecture Slides: C How to Program by Paul Deital &
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Chapter 3: Input/Output
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with output formatting.
#include int main() { char *string1=”C++”; char *string2=”Program”; int m=strlen(string1); int n=strlen(string2); for(int i=1;i
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ How to Program, 8/e © Copyright by Pearson Education, Inc. All Rights Reserved.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 13: Exam 1 Preview.
Chapter 13 Stream Input/Output C++ How to Program, 9/e © Copyright 2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Topic 2 Input/Output.
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Chapter 21 - C++ Stream Input/Output Stream Manipulators
Output Stream Formatting
Chapter 21 - C++ Stream Input/Output
Formatting Screen Input/Output
Standard Input/Output Streams
Standard Input/Output Streams
File I/O Streams, files, strings 1 1.
Manipulators CSCE 121 J. Michael Moore
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 12 - C++ Stream Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 3: Expressions and Interactivity
Programming with ANSI C ++
C++ Stream Input/Output
Chapter 12 - C++ Stream Input/Output
Input/Output Streams, Part 2
Presentation transcript:

The C++ Programming Language Streams

Contents u Output Stream u Input Stream u Formatting u Manipulators u 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 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);

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

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

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

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 u istream::get(char &)} reads a single character into its argument main() { char c; while ( cin.get(c) ) cout << c; }

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

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

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

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

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

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

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

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

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)

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

Notes

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

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)

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

Floating-Point Output cout << << '\n'; // cout.setf(ios::scientific,ios::floatfield); cout << << '\n'; // e+03 cout.setf(ios::fixed,ios::floatfield); cout << << '\n'; // cout.precision(8); cout << << '\n'; // cout.precision(4); cout << << '\n'; // 1235

Notes u 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 > 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 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

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;// d cout << setw(4) << setfill('#') << '(' << 12 << ")\n"; // (##12)

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 ();

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;