Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.

Slides:



Advertisements
Similar presentations
File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
Advertisements

CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Standard.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
C++ Introduction. Why Learn C++? Very powerful and respected prog. Lang. Very powerful and respected prog. Lang. Highly respected in Academics Highly.
C++ crash course Class 3 designing C++ programs, classes, control structures.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
Vectors and Grids Eric Roberts CS 106B April 8, 2009.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Chapter 15 Strings as Character Arrays
Why Use Namespaces? Classes encapsulate behavior (methods) and state (member data) behind an interface Structs are similar, but with state accessible Classes.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
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.
Streams One of the themes of this course is that everything can be reduced to simple (and similiar) concepts. Streams are one example. Keyboard and Screen.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too.
1 Today’s Objectives  Announcements Homework #5 is due next Monday, July 24. Since this date is so close to the end of the semester, no late assignments.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
Inheritance - 3. Virtual Functions Functions defined as virtual are ones that the base expects its derived classes may redefine. Functions defined as.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
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.
Working with Batches of Data
Standard C++ Input/Output and String Classes
Note: Some of the slides are repeated from Introduction to C++
Chapter 14: Sequential Access Files
C++ Exceptions.
ifstreams and ofstreams
C++ Standard Library.
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Copyright © 2003 Pearson Education, Inc.
File I/O Streams, files, strings 1 1.
Interactive I/O Input from keyboard Must prompt user User friendly
Basic File I/O and Stream Objects
Today’s Lecture I/O Streams Tools for File I/O
Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
CS150 Introduction to Computer Science 1
File I/O in C++ I.
CS150 Introduction to Computer Science 1
File I/O.
CHAPTER 4 File Processing.
Reading from and Writing to Files
C++ Introduction - 3.
ifstreams and ofstreams
Std Library of C++.
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

std Library of C++ Part 2

vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in a vector has an associated integer index (like an array element) Each object in a vector has an associated integer index (like an array element) As with string, vector class itself manages memory associated with the collection. As with string, vector class itself manages memory associated with the collection.

Class template vector is a class template vector is a class template Templates allow single class (or function) definition to be used on a variety of types Templates allow single class (or function) definition to be used on a variety of types So one vector variable/object can hold ints So one vector variable/object can hold ints Another vector object can hold strings Another vector object can hold strings A third vector object can hold objects of user defined classes like Sales_item A third vector object can hold objects of user defined classes like Sales_item

vector example #include #include using std::vector; using std::vector; vector ivec; // ivec holds objects of type int vector ivec; // ivec holds objects of type int vector Sales_vec; // holds Sales_items vector Sales_vec; // holds Sales_items The type of object to be held in a vector is passed within angle brackets The type of object to be held in a vector is passed within angle brackets

Types Vector is not a type; it is a class template Vector is not a type; it is a class template The type is known only after the arguments of the class template are specified The type is known only after the arguments of the class template are specified So vector is a type So vector is a type And vector is another type. And vector is another type.

vector initialization vector v1; vector v1; vector that holds objects of type T; vector that holds objects of type T; Default constructor Default constructor v1 is empty v1 is empty vector v2(v1); vector v2(v1); v2 is a copy of v1 v2 is a copy of v1 vector v3(n, i); vector v3(n, i); v3 has n elements with value i v3 has n elements with value i

vector initialization contd. vector ivec4(10, -1); vector ivec4(10, -1); // 10 elements, each initialized to -1 // 10 elements, each initialized to -1 vector svec(10, "hi!"); vector svec(10, "hi!"); // 10 strings, each initialized to "hi!" // 10 strings, each initialized to "hi!"

vector.push_back() push_back() method takes an element value and puts that at the back of a vector push_back() method takes an element value and puts that at the back of a vector We can say that is pushes the element onto the back or end of the vector. We can say that is pushes the element onto the back or end of the vector. This involves creating space for a new element at the end of the vector. This involves creating space for a new element at the end of the vector.

Adding elements to a vector // read words from the standard input and // read words from the standard input and // store them as elements in a vector // store them as elements in a vector string word; string word; vector text; // empty vector vector text; // empty vector while (cin >> word) { while (cin >> word) { text.push_back(word); text.push_back(word); // append word to text // append word to text }

Accessing elements of a vector // reset the elements in the vector to zero // reset the elements in the vector to zero for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != ivec.size(); ++ix) ix != ivec.size(); ++ix) ivec[ix] = 0; ivec[ix] = 0;

Subscripting does not add!! vector ivec; // empty vector vector ivec; // empty vector for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != 10; ++ix) ix != 10; ++ix) ivec[ix] = ix; ivec[ix] = ix; // disaster: ivec has no elements // disaster: ivec has no elements An element must exist in order to subscript it; An element must exist in order to subscript it; Elements are not added when we assign through a subscript. Elements are not added when we assign through a subscript.

Correct way to add for (vector ::size_type ix = 0; for (vector ::size_type ix = 0; ix != 10; ++ix) ix != 10; ++ix) ivec.push_back(ix); ivec.push_back(ix); // ok: adds new element with value ix // ok: adds new element with value ix

Assignment 3C Read words from standard input till end of input, into a vector. Read words from standard input till end of input, into a vector. Write out all words (by retrieving them from the vector) to standard output separating each word by a newline. Write out all words (by retrieving them from the vector) to standard output separating each word by a newline. Test your program with small, medium and very large text input files. Notice how fast the program runs. Test your program with small, medium and very large text input files. Notice how fast the program runs.

Assignment 3C contd. Optional: For the ambitious, time stamp and print out the time taken by the read part of the program. Optional: For the ambitious, time stamp and print out the time taken by the read part of the program.

IO Library Streams We will have a very quick look at IO Library streams. We will have a very quick look at IO Library streams. C++ std library provides a family of types and objects that support I/O. C++ std library provides a family of types and objects that support I/O.

IOStream The iostream header has: The iostream header has: istream (input stream) type, which supports input operations istream (input stream) type, which supports input operations cin (pronounced see-in) an istream object that reads the standard input cin (pronounced see-in) an istream object that reads the standard input ostream (output stream) type, which provides output operations ostream (output stream) type, which provides output operations cout (pronounced see-out) an ostream object that writes to the standard output cout (pronounced see-out) an ostream object that writes to the standard output

Facilities Used So Far Some facilities that we used were: Some facilities that we used were: operator >>, which is used to read input from an istream object operator >>, which is used to read input from an istream object operator <<, which is used to write output to an ostream object operator <<, which is used to write output to an ostream object getline function, which takes a reference to an istream and a reference to a string and reads a word from the istream into the string getline function, which takes a reference to an istream and a reference to a string and reads a word from the istream into the string

Reading and Writing Files So far we have used the IO types and objects to read and write from stdin and stdout So far we have used the IO types and objects to read and write from stdin and stdout But programs often need to read and write named files (and not use redirection) But programs often need to read and write named files (and not use redirection) Ideally we should be able to use >> and > and << to operate on a named file too.

File Stream fstream header defines the types used to read and write named files: fstream header defines the types used to read and write named files: ifstream type reads from a file ifstream type reads from a file ofstream type writes to a file ofstream type writes to a file >>, >, << operators can be used to i/o on file streams

… File Stream ifstream infile; // unbound input file stream ofstream outfile; // unbound output file stream ifstream infile; // unbound input file stream ofstream outfile; // unbound output file stream infile and outfile need to be bound to a named file. infile and outfile need to be bound to a named file. infile.open("in"); // open file named "in" in the current directory infile.open("in"); // open file named "in" in the current directory outfile.open("out"); // open file named "out" in the current directory outfile.open("out"); // open file named "out" in the current directory

Testing open success Did open succeed?? Did open succeed?? // check that the open succeeded // check that the open succeeded if (!infile) { if (!infile) { cerr << "error: unable to open input file: " cerr << "error: unable to open input file: " << ifile << endl; << ifile << endl; return -1; return -1; } }

Defining ifstream object and opening file in one stmt. ifstream infile("in"); ifstream infile("in"); Defines/declares infile object and also opens file “in” and binds it to infile and opens the file. Defines/declares infile object and also opens file “in” and binds it to infile and opens the file. Success/failure check: if (infile) … Success/failure check: if (infile) …

Reading/Writing Reading a string from an ifstream object Reading a string from an ifstream object string word; string word; infile >> word; //Reads next string from infile infile >> word; //Reads next string from infile // into word // into word Writing a string into an ofstream object Writing a string into an ofstream object ofstream outfile(“out”); ofstream outfile(“out”); outfile << “Hello World”; outfile << “Hello World”;

Example Programs See filecin.cpp See filecin.cpp See fileio.cpp See fileio.cpp

String Streams In-Memory input/output where a stream is attached to a string (in program memory) In-Memory input/output where a stream is attached to a string (in program memory) istringstream type reads from a string istringstream type reads from a string istringsteam strm(line); istringsteam strm(line); Given that line is a string Given that line is a string strm is an istringstream bound to the string line strm is an istringstream bound to the string line strm >> strword; strm >> strword; Reads next word from line into strword Reads next word from line into strword

Counting words & lines See countWordNLine.cpp (Not from book code) See countWordNLine.cpp (Not from book code)

Assignment 3d Write a LineSizeSearch program that accepts one (and only one) agrument which is the input text filename. [Don't forget to check number of arguments passed to main. If it is not the expected number then immediately print an error message, followed by "Usage: 'argv[0]' file-name” and then exit.] Write a LineSizeSearch program that accepts one (and only one) agrument which is the input text filename. [Don't forget to check number of arguments passed to main. If it is not the expected number then immediately print an error message, followed by "Usage: 'argv[0]' file-name” and then exit.]

Assignment 3d 1) Read all lines from an input text file into memory (Till EOF). 1) Read all lines from an input text file into memory (Till EOF). 2) Then print stats about file (no. of lines), and print entire file with line number, line size: before each line. 2) Then print stats about file (no. of lines), and print entire file with line number, line size: before each line.

Assignment 3d 3) Now allow user to search for any line of a specified line size. 3) Now allow user to search for any line of a specified line size. Show all the matching lines, preceded by the line number, line size Show all the matching lines, preceded by the line number, line size OR, if no matching lines are found, a message to that effect. OR, if no matching lines are found, a message to that effect. Allow user to keep searching for as many times as he wants. Allow user to keep searching for as many times as he wants. On user keying in End-Of-Data (Ctrl-D), Quit program On user keying in End-Of-Data (Ctrl-D), Quit program

More Details For more details on IO Library and streams, interested students can read Chapter 8: IO Library from course book. For more details on IO Library and streams, interested students can read Chapter 8: IO Library from course book.

Book Source Code Copyright Note The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides. The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides.