UEE1303(1070) S 12 Object-Oriented Programming in C++

Similar documents
CS2141 Software Development using C/C++ Stream I/O

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Fig: iostream class hierarchy

Advanced I/O Concepts

Streams in C++ Stream concept. Reference information. Stream type declarations

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

I/O Streams and Standard I/O Devices (cont d.)

Objects and streams and files CS427: Elements of Software Engineering

C++ Programming Lecture 10 File Processing

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

IS 0020 Program Design and Software Tools

Input and Output File (Files and Stream )

What we will learn about this week:

Fall 2017 CISC/CMPE320 9/27/2017

by Pearson Education, Inc. All Rights Reserved. 2

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

Module 11 The C++ I/O System

Chapter 12. Streams and File I/O

Chapter 3 - Notes Input/Output

Lecture 9. Introduction

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

CS11 Advanced C++ Lecture 2 Fall

C++ Input/Output: Streams

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Chapte t r r 9

C++ does not, as a part of the language, define how data are sent out and read into the program

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Chapter 14 Sequential Access Files

Unit-V File operations

UEE1302 (1102) F10: Introduction to Computers and Programming

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Input/Output Streams: Customizing

UNIT V FILE HANDLING

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Chapter-12 DATA FILE HANDLING

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Object Oriented Programming In C++

Week 3: File I/O and Formatting 3.7 Formatting Output

Writing a Good Program. 7. Stream I/O

C++ Input/Output Chapter 4 Topics

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

BITG 1113: Files and Stream LECTURE 10

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

Lecture 3 The character, string data Types Files

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Chapter 21 - C++ Stream Input/Output

C++ files and streams. Lec 28-31

Streams - Object input and output in C++

Generate error the C++ way

Engineering Problem Solving with C++, Etter/Ingber

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 21 - C++ Stream Input/Output

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Stream States. Formatted I/O

Lecture 5 Files and Streams

COMP322 - Introduction to C++

CS3157: Advanced Programming. Outline

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

System Design and Programming II

CS201 Solved MCQs.

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

C++ How to Program 14.6

Chapter 8 File Processing

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Introduction. Lecture 5 Files and Streams FILE * FILE *

CS 103 Unit 14 - Streams

Fundamentals of Programming Session 27

Introduction to C++ (Extensions to C)

EP241 Computing Programming

Developed By : Ms. K. M. Sanghavi

Introduction to Standard C++ Console I/O. C++ Object Oriented Programming Pei-yih Ting NTOU CS

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

CPE Summer 2015 Exam I (150 pts) June 18, 2015

COMP322 - Introduction to C++

Chapter 11 Customizing I/O

Standard I/O in C and C++

Due Date: See Blackboard

Definition Matching (10 Points)

10/23/02 21:20:33 IO_Examples

File I/O Christian Schumacher, Info1 D-MAVT 2013

C++ Structures Programming Workshop 2 (CSCI 1061U)

Chapter 11 Customizing I/O

Random File Access. 1. Random File Access

Programming in C/C

We will exclusively use streams for input and output of data. Intro Programming in C++

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Page 1

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

Short Notes of CS201

Transcription:

Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member functions File stream ifstream and ofstream member functions access binary files String stream istringstream and ostringstream member functions Hung-Pin(Charles) Wen UEE1303(1070) L06 2 I/O Stream Stream Class A stream is a sequence of bytes used in an input or output operation C++ provides both low-level and high-level input/output (I/O) capabilities Low-level I/O is unformatted bytes are transferred into and out from memory without regard to the type of data for high-volume, high-speed processing High-level I/O is formatted bytes are grouped into meaningful units such as integers, doubles, and class object types Hung-Pin(Charles) Wen UEE1303(1070) L06 3 The istream class includes a definition of the extraction operator >> The ostream class includes a definition of the insertion operator << The iostream is short for input and output stream istream ios_base ios iostream ostream Hung-Pin(Charles) Wen UEE1303(1070) L06 4

Understand cin and cout When you include iostream at the top of your program files, you gain access to these functions cin and cout cin and cout are objects and members of the class can use operators such as << and >> polymorphism: can generate different machine instructions when placed with different types of variables Member Functions of istream (1/2) In C++, the easiest way to read a character is to use cin with the extraction operator Extraction operator is an overloaded function named operator>>() cin >> somevariable; Besides the overloaded extraction operator, including iostream provides other input functions most compilers support other istream member functions, such as eof(), bad(), and good() Hung-Pin(Charles) Wen UEE1303(1070) L06 5 Hung-Pin(Charles) Wen UEE1303(1070) L06 6 Member Functions of istream (2/2) As an object, cin contains member functions istream function get() use those member functions with the dot operator and the function name prototype istream& get(char &); int get(); istream& get(char *str, int len, char c= \n ); purpose extract unformatted data from a stream getline() istream& getline(char *str, get a line of data int len, char c = \n ); from an input stream ignore() istream& ignore(int length = 1, char c = \n ); extract and discard characters Use get() Function (1/3) The get() function takes a character argument and returns a reference to the object that invoked it prototype: istream& get(char &); multiple get() function calls can be chained char first, middle, last; cin.get(first); cin.get(middle).get(last); //why? Hung-Pin(Charles) Wen UEE1303(1070) L06 7 Hung-Pin(Charles) Wen UEE1303(1070) L06 8

Use get() Function (2/3) Use get() Function (3/3) cin.get() can retrieve any character, including letters, numbers, punctuation, and white space such as the character generated by pressing the Enter key Most compilers overload get() so that it can also take no argument Prototype: int get(); Example: cout << "Press any key to continue"; c=cin.get(); //c: casted to an integer Hung-Pin(Charles) Wen UEE1303(1070) L06 9 The istream class get() function is overloaded so that it can take two or three arguments istream& get(char *str, int len, char c = '\n'); allow you to input a string of characters 1st argument is a pointer that holds the address of the string (necessary) 2nd argument is the number of characters that will be stored (necessary) 3rd argument is the character that terminates the entry, often called the delimiter character See lec6-1.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 10 Prototype: Use getline() Function istream& getline(char *str, int len, char c='\n'); The getline() function reads a line of text at the address represented by str It reads until it reaches either the length or the character used as the third argument See lec6-1.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 11 Use ignore() Function using the ignore() function to ignore or skip additional characters left in input stream Prototype istream& ignore(int length = 1, char c = '\n'); where length is the maximum number of characters to ignore, and c is the consumed character that stops the ignore() function The delim character itself is also discarded See lec6-1.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 12

Member Functions of ostream (1/2) The concepts you have learned while studying the cin object apply to the cout object as well It is a member of the ostream class, which supports member functions and overloaded operators Example: the operator<<() function Besides member functions, the cout object also has data members, or states Member Functions of ostream (2/2) Other ostream member functions include put(), flush(), eof(), bad(), and these functions shown in table istream function setf() unsetf() prototype purpose fmtflags setf(fmtflags); tasks arguments that set the bits of cout. fmtflags unsetf(fmtflags); precision() int precision(int); tasks arguments that unset the bits of cout. set precision width() int width(int); set field width Hung-Pin(Charles) Wen UEE1303(1070) L06 13 Hung-Pin(Charles) Wen UEE1303(1070) L06 14 setf() and unsetf() Functions (1/3) Many of the states of cout are contained in a long integer field each bit represents some condition of the object example: bit that represents show positive sign might be turned on The arguments that determine the state of the cout object are called format flags or state flags all begin with ios:: setf() and unsetf() Functions (2/3) ios::left - left-justifies output within the field size, which may be set by the width() function ios::right - right-justifies output within the field size ios::dec - formats numbers in decimal (base 10) ios::showpos - inserts + before positive numbers ios::showpoint - displays the decimal point and six significant digits for all floating-point numbers Hung-Pin(Charles) Wen UEE1303(1070) L06 15 Hung-Pin(Charles) Wen UEE1303(1070) L06 16

setf() and unsetf() Functions (3/3) setf(), a member of ios class, takes arguments that set the bits of cout cout.setf(ios::showpos); turns on the bit that forces the display of + with positive numbers cout.setf(ios::showpos ios::dec ios::showpoint); cout << 4.0; +4.00000 unsetf() deselects the bit(s) cout.unsetf(ios::showpos); Use width() Function (1/2) width() changes the output field width by default, the argument is right-aligned use ios::left to change the default alignment The following statements produce three blanks followed by 13, for a total output of five characters: cout.width(5); cout << 13; // or cout << setw(5) << 13; 13 Hung-Pin(Charles) Wen UEE1303(1070) L06 17 Hung-Pin(Charles) Wen UEE1303(1070) L06 18 Use width() Function (2/2) If value provided for width() is not large enough for the displayed value, it is disregarded cout.width(2); cout << 5555; 5555 Applies only to the first subsequent field to be output call it each time you want a width specification to take effect Use precision() Function Use to control the number of significant digits in the output For example, the constant 12.98765 contains seven digits; you can display four digits as follows: cout.precision(4); cout << 12.98765; //displays 12.99 Unlike width(), precision() applies to all subsequent output fields until the precision is reset by another call to it Hung-Pin(Charles) Wen UEE1303(1070) L06 19 Hung-Pin(Charles) Wen UEE1303(1070) L06 20

Stream Class fstream contains typedefs that provide aliases for the template specializations in the class ifstream, ofstream, and fstream ifstream istream ios_base ios iostream fstream ostream ofstream Understand Computer Files Data file: contains records that are logically related A delimiter character separates data fields Last-name field First-name field Salary field Armanetti Robin 325.77 Banier Carmen 399.24 Claxton Dustin 467.85 Damell Brittany 502.11 Finn Eric 545.27 Record for Carmen Banter Group of related files is often stored in a database Hung-Pin(Charles) Wen UEE1303(1070) L06 21 Hung-Pin(Charles) Wen UEE1303(1070) L06 22 Simple File Output (1/5) To perform file processing, <iostream> and <fstream> must be included in your program file To perform file output, instantiate your own member of the fstream or ofstream class ofstream outfile( Data.txt ); if the file does not exist, it is created if the file already exists, it is overwritten Simple File Output (2/5) Use two backslashes in a pathname example: c:\\datafolder\\data.txt /user/home/9913052/data.txt If you do not provide a filename when you instantiate an fstream or ofstream object, no file is opened explicitly open the file later with open(): ofstream outfile; outfile.open( Data.txt ); Object-Oriented Programming Using C++, Fourth Edition 23 Hung-Pin(Charles) Wen UEE1303(1070) L06 24

Simple File Output (3/5) The fstream and ofstream constructors and the open() function are overloaded to accept a second argument to indicate a file mode File mode tells C++ how to open the file: ios::in open the file for input ios::out (default) open the file for output ios::app append the file (rather than recreate it) ios::ate open an existing file (either input or output) and seeks the end. ios::binary open the file for binary I/O Hung-Pin(Charles) Wen UEE1303(1070) L06 25 Simple File Output (4/5) An open() operation (whether explicit or through the constructor) can fail for several reasons attempt to open an existing file using the wrong path attempt to create a file on a storage device that is full attempt to open a file using an invalid mode To check whether an open() has failed, you can try several methods, using the out object itself or its good() or bad() functions Hung-Pin(Charles) Wen UEE1303(1070) L06 26 Simple File Output (5/5) Once the file is open, you can write to it as follows: myfile << "This is going to the disk"; After you have written to a file, you do not need to explicitly execute any sort of close file when an fstream or ofstream object goes out of scope, a destructor is called that closes the file To close a file before the file object goes out of scope, use close(): myfile.close(); Hung-Pin(Charles) Wen UEE1303(1070) L06 27 An Example for File Output #include <iostream> #include <fstream> #include <iomanip> using namespace std; lec6-3.cpp int main() { fstream myfile; myfile.open( test.dat, ios::in); if (myfile.good()) cout << File opened! << endl; else cout << Cannot open file! << endl; return 0; Hung-Pin(Charles) Wen UEE1303(1070) L06 28

Simple File Input (1/2) To read a file from within a program, create an instantiation of the ifstream class Example: ifstream somedata("data.txt"); Name of instantiated object can be any legal identifier The file is identified by the filename used as a parameter to the ifstream object s constructor Simple File Input (2/2) open() and close() work with ifstream objects Appropriate file modes can be used as arguments to ifstream constructor or to open() statements When an ifstream object goes out of scope, the file is closed automatically You can call close() to free resources Hung-Pin(Charles) Wen UEE1303(1070) L06 29 Hung-Pin(Charles) Wen UEE1303(1070) L06 30 An Example for File Input Write/Read Objects (1/2) 20 50.9 30.7 46.6 89 90.8 24 50 50 #include <fstream> lec6-3.cpp #include <iostream> using namespace std; int main() { double sum=0, t; int count=0; ifstream in( data.txt, ios::in); if (!in) cout << Cannot open file! << endl; while (in >> t) { sum += t; count++; cout << avg= << sum/count << endl; Hung-Pin(Charles) Wen UEE1303(1070) L06 31 class CStu { int sid; string name; double gpa; friend ostream& operator<<(ostream&, CStu); friend istream& operator>>(istream&, CStu&); ostream& operator<<(ostream& out, CStu s) { out << s.sid << << s.name << << s.gpa << endl; return out; istream& operator>>(istream& in, CStu& s) { in >> s.sid >> s.name >> s.gpa; return in; lec6-4.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 32

Write/Read Objects (2/2) #include <fstream> #include <iostream> using namespace std; int main() { CStu a; ofstream out; out.open( out6-4.txt ); cout << Enter id, name, and gpa\n ; while (cin >> a) { out << a << endl; cout << Enter id, name, and gpa\n ; out.close(); return 0; lec6-4.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 33 Write/Read Binary Files Reading or writing a binary file need to use read() and write() in <fstream> read n chars from the binary file to a buffer istream& istream::read(char *t, int n); read n chars from the buffer and write them to the binary file ostream& ostream::write(const char *t, int n); write(p1,50); //write 50 chars to disk read(p2,30); //read 30 chars Hung-Pin(Charles) Wen UEE1303(1070) L06 34 Example for Binary I/O (1/2) #include <fstream> lec6-5.cpp #include <iostream> using namespace std; int main() { ofstream out( dat6-4.txt", ios::out ios::binary); if (!out) { cout << dat6-4.txt is not opened"; return -1; for (int i=1; i<200; i+=2) { out.write((char *)&i, sizeof(i)); // write 100 odd numbers out.close(); Example for Binary I/O (2/2) ifstream inp( dat6-4.txt", ios::in ios::binary); inp.seekg(15*sizeof(int)); //move to 16th odd integers int x; for (int i=1; i<50 &&!inp.eof(); ++i) { inp.read((char *)&x, sizeof(i)); //read each odd number cout << x << " "; if (!(i%=10)) cout << endl; cout << endl; inp.close(); lec6-5.cpp Hung-Pin(Charles) Wen UEE1303(1070) L06 35 Hung-Pin(Charles) Wen UEE1303(1070) L06 36

Stream Class stringstream contains typedefs that provide aliases for the template specializations in the class ifstream, ofstream, and fstream Input and output is string object istream istringstream iostream stringstream ostream ostringstream Hung-Pin(Charles) Wen UEE1303(1070) L06 37 Examples for istringstream An example for istringstream string buffer; lec6-6.cpp getline(cin, buffer); istringstream instr(buffer); long value = 0; double data = 0.0; instr >> value >> data;... istringstream instr;... getline(cin, buffer); instr.clear(); instr.str(buffer);... Hung-Pin(Charles) Wen UEE1303(1070) L06 38 Examples for ostringstream Examples ostringstream outstr; lec6-6.cpp double number = 2.5; outstr << number = << (3 * number/2); string output = outstr.str(); stringstream ss; int data=200; int result; ss<<data; //push data into ss ss>>result; //pop result from ss Summary cout and cin are members of a class >> is overloaded to input all built-in types The ostream class provides useful output functions: setf(), unsetf(), width(), and precision() To perform file output, you must instantiate your own member of the fstream or ofstream class stringstream provides convenient conversion between stream and string Hung-Pin(Charles) Wen UEE1303(1070) L06 39 Hung-Pin(Charles) Wen UEE1303(1070) L06 40