Object Oriented Programming in C++ Chapter 11 STL.

Slides:



Advertisements
Similar presentations
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
Advertisements

File streams Chapter , ,
I/O Streams as an Introduction to Objects and Classes
CPSC 231 D.H. C++ File Processing 1 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
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.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 3: Input/Output
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
Standard Template Library Programming paradigm: generic programming the decomposition of programs into components which may be developed separately and.
CHAPTER 3 INPUT/OUTPUT. In this chapter, you will:  Learn what a stream is and examine input and output streams  Explore how to read data from the standard.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
C++ Streams Lecture-2.
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
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:
Fundamental File Processing Operations C++
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
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 &
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
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
#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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
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.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
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,
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
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.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
CS212: Object Oriented Analysis and Design
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
CPSC 231 D.H. C++ File Processing
Standard Input/Output Streams
Standard Input/Output Streams
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 3: Input/Output
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 4 INPUT AND OUTPUT OBJECTS
Programming with ANSI C ++
C++ Programming Lecture 8 File Processing
Input/Output Streams, Part 2
Presentation transcript:

Object Oriented Programming in C++ Chapter 11 STL

Standard Template Library STL providing generic programming by these three components: Containers Iterators Algorithms

Containers STL Typical Containers Interfaces Constructors Element access Element insertion Destructor Iterators

Many algorithms return an identification of an element in a container (list, vector, map, etc.). Such identifications usually have type “iterator”. iterators know the operator ++ “sequences” (of elements in a container) are specified by two iterators, pointing to the first and last+1 element, resp. For example: list ::iterator p = find(li.begin(),li.end(),42); if (p!=li.end()) { list ::iterator q = find(++p,li.end(),42); }

Sequence Containers Vector Deque List

Vector & Deque Example #include using namespace std; const int SIZE = 100; double sum(const deque &dq) { deque ::const_iterator p; double s = 0; for (p=dq.begin(); p != dq.end(); ++p) s += *p ; return s; }

int main() { vector vec(SIZE, 0); deque deq; int i; double sumTotal; // init and output vec for(i = 0; i < SIZE; i++){ vec[i] = i * 0.6; cout << vec[i] <<"\t"; } deq.push_front(vec.front()); // add an element to the front deq.push_back(vec.back()); // add an element to the back // Insert the remaining elements from the vector between // the first and last deque elements deq.insert(deq.begin()+1, vec.begin()+1, vec.end()-1); sumTotal = sum(deq); cout << "The sum of the deque is : " << sumTotal << endl; }

Stack Example #include using namespace std; int main() { stack > str_stack; string quote[3] = {"The wheel that squeaks the loudest\n", "Is the one that gets the grease\n", "Josh Billings\n" }; for (int i =0; i < 3; ++i) str_stack.push(quote[i]); while (!str_stack.empty()) { cout << str_stack.top(); str_stack.pop(); }

Algorithms Sorting algorithms Nonmutating sequence algorithms Mutating sequence algorithms Numerical algorithms

Quick Sort #include using namespace std; const int N = 5; int main() { int d[N], i, *e = d + N; for (i = 0; i < N; ++i) d[i] = rand(); sort(d, e); for (i = 0; i < N; ++i) cout << d[i] << '\t'; }

Nonmutating sequence algorithms #include using namespace std; int main() { string words[5] = { "my", "hop", "mop","hope", "cope"}; string* where; where = find(words, words + 5, "hop"); cout << *++where << endl; //mop sort(words, words + 5); where = find(words, words + 5, "hop"); cout << *++where << endl; //hope }

Mutating sequence algorithms #include using namespace std; int main() { string first_names[5] = {"laura", "nira", "buzz", "debra", "twinkle"}; string last_names[5] = {"peri", "peri","berry", "berry", "star"}; vector names(first_names, first_names + 5); vector names2(10); vector ::iterator p; copy(last_names, last_names + 5, names2.begin()); copy(names.begin(), names.end(), names2.begin() + 5); reverse(names2.begin(), names2.end()); for (p = names2.begin(); p != names2.end(); ++p) cout << *p <<'\t'; }

Object Oriented Programming in C++ Chapter 12 Input Output

I/O Streams: cin, cout, cerr cin is an object of class istream and is “tied” to the standard input device, normally the keyboard. cout is an object of class ostream and is “tied” to the standard output device, normally the screen. cerr is also an object of class ostream and is linked with the standard error device, normally the screen.

iostream Library Header Files basic stream input and output operations formatted I/O with parametrized stream manipulators file processing formatting with character arrays

Stream Classes ios istreamostream ofstreamiostreamifstream fstream

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

The put Member Function main() { char c = ‘X’ ; cout.put(c); cout.put(c).put(‘Y’); }

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

Using get with no arguments main() { char ch; while( (ch = cin.get()) != EOF) cout.put(ch); }

The 3-argument istream::get() reads at most n-1 characters stores input into a vector of characters stores the null character at the end stops reading when delimeter is encountered delimeter will be the next character to read

main() { char v[80]; cin.get(v, 80, ‘\n’); char ch; if (cin.get(ch) && ch != ‘\n’) cout << “line is too long\n” ;...

The ignore Istream Member 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.

The putback Istream Member istream& istream::putback(char ch); places the character argument back onto the input stream #include istream& skipblanks(istream& s) { char ch; while( (ch=s.get()) == ‘ ‘) ; s.putback(ch); return s; }

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 operation. stdio=040000//flush after each char. }; //... };

The flags Member Function A set of formatting information using the function flags(). int options= ios::right | ios::hex | ios::fixed; cout.flags(options);

flags() (continued) // 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);

The setf(long) and unsetf(long) Member Functions 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.

Formatting Functions class ios { //... public: int width(int w); char fill(char); int precision(int); long setf(long);... };

The width Member Function Allows us to specifie the minimum number of characters to be used for the next numeric or string output operations. cout.width(5);

The fill Member function Allows us to specify the fill character cout.fill(‘#’); (remains in effect until changed)

The precision() Member Function specifies the floating point precision the default is 6 remains set until next call to precision cout.precision(8);

Example cout.width(5); cout.fill(‘*’); cout.setf(ios::left, ios::adjustfield); cout << “x = “ << x ; cout.setf(ios::scientific, ios::floatfield); cout << ; output: e+03 cout.setprecision(7); cout << << ‘\n’; output:

Manipulators ios& oct(ios&); ios& dec(ios&); ios& hex(ios&); ostream& endl(ostream&); ostream& ends(ostream&); ostream& flush(ostream&); istream& ws(istream&); smanip setbase(int) smanip setfill(int); smanip setprecision(int); smanip setw(int);...

Example #include... int x = 12; cout << octal << x << endl;... cin >> octal >> x; … x=123; cout << “x = “ << setw(5) << setfill(‘*’)<< x << endl ;

User-Defined Manipulators main() { cin >> ws >> x; cout << tab << “x = “ << tab << x << endl; }

class ostream : public virtual ios { //... public: ostream& operator<<(ostream& (*f) (ostream&)) { return (*f)(*this); } //... }; ostream& tab(ostream& os) { return os << ‘\t’ ; }

Files and Streams class ostream : public virtual ios { //... public: ostream& flush(); ostream& seekp(streampos); ostream& seekp(streamoff, seek_dir); streampos tellp(); //... };

Seek Direction class ios { //... public: enum seek_dir { beg=0, cur=1, end=2 }; //... };

Opening an Output File ofstream of(“data”, ios::out); in ios::out mode the file is truncated by default, ofstream implies that the file is opened with the out mode. ofstream of(“data”);

File Open Modes ios::appWrite output to end of file ios::ateMove to end of file. Allows data to be written anywhere ios::inOpen file for input ios::outOpen file for output ios::truncerase file contents ios::nocreate if file does not exist, the operation fails ios::noreplaceif the file exists, the operation fails

Testing the Success of open if ( ! of )... Possible errors: opening a non-existent file attempting to read without permission attempting to write with no disk space

Closing a File The file is implicitly closed when the ofstream object is destroyed. We can explicitly close a file: of.close();

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

Opening an Input File By default files are open with in mode: ifstream if(“indata”, ios::in); ifstream if(“indata);

Repositioning a File Reposition pointer at the beginning: if.seekg(0) reposition to the nth byte: if.seekg(n); position y bytes back from end if.seekg(y, ios::end); position at end of file: if.seekg(0, ios::end);

tellg and tellp tellg() and telp() return the current position: long pos = if.tellg();

Example - Input #include 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; }

Query Example #include main() { char name[10]; int quantity; char item[10]; ifstream inf("inventory", ios::in); if( !inf ) { cerr << "Cannot open file\n"; exit(1); } 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; }