Objects and streams and files CS427: Elements of Software Engineering

Similar documents
Week 5: Files and Streams

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

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

COMP322 - Introduction to C++

Input and Output File (Files and Stream )

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

BITG 1113: Files and Stream LECTURE 10

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

C++ Input/Output: Streams

Chapter 3 - Notes Input/Output

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

Getting started with C++ (Part 2)

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

C++ Programming Lecture 10 File Processing

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

Streams - Object input and output in C++

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

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

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

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

COMP322 - Introduction to C++

EP241 Computing Programming

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

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

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

Chapter 12. Streams and File I/O

Introduction to C++ (Extensions to C)

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

PROGRAMMING EXAMPLE: Checking Account Balance

C++ Programming Classes. Michael Griffiths Corporate Information and Computing Services The University of Sheffield

Lecture 3 The character, string data Types Files

C Legacy Code Topics. Objectives. In this appendix you ll:

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

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

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

Writing a Good Program. 7. Stream I/O

Chapte t r r 9

CS201 Solved MCQs.

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

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. 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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

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

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

Unit 1 : Principles of object oriented programming

Chapter 12 - C++ Stream Input/Output

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

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

CS3157: Advanced Programming. Outline

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Quick Guide. Advertisements

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

Consider the following example where a base class has been derived by other two classes:

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Fundamental File Processing Operations 2. Fundamental File Processing Operations

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

BITG 1233: Introduction to C++

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

Chapter 3. Numeric Types, Expressions, and Output

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

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

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

Fig: iostream class hierarchy

by Pearson Education, Inc. All Rights Reserved. 2

For Teacher's Use Only Q No Total Q No Q No

Module 11 The C++ I/O System

Object Oriented Programming CS250

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

Lecture 14: more class, C++ streams

Software Design & Programming I

Window s Visual Studio Output

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Lecture 9. Introduction

EL2310 Scientific Programming

SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) which generates a random number in the range of 0 to n-1. For example;

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Computational Physics

CSE 333 Lecture 9 - intro to C++

Fundamentals of Programming CS-110. Lecture 2

CSCE 206: Structured Programming in C++

Chapter 14 Sequential Access Files

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

What we will learn about this week:

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Come and join us at WebLyceum

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

Chapter 15 - C++ As A "Better C"

Stream States. Formatted I/O

C++ basics Getting started with, and Data Types.

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

Engineering Problem Solving with C++, Etter/Ingber

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

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

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS24 Week 3 Lecture 1

Transcription:

Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18

Today s topics 1 Recall...... Dynamic Memory Allocation... Encapsulation The stack example again 2 Constructor 3 Destructors 4 Streams as examples of Objects 5 code, cin methods manipulators 6 Files open CS427 Objects and streams and files 2/18

Recall...... Dynamic Memory Allocation In C++ dynamic memory allocation is achieved using new and delete. Example int *contents; contents = new int[20];... delete [] contents; Note: unlike calloc and malloc in C, new will work with any data type, including user-defined types such as class. Also, casting is not required. CS427 Objects and streams and files 3/18

Recall...... Encapsulation Encapsulation incorporating the data associated with an entity, and the methods of manipulating that data, into a single abstract data type. Usually, Public methods provide the interface to an object, while its internal state is represented by private data. In C++, encapsulation is usually achieved using the class construct.............................................................................. In today s class we ll quickly revise what we did in Lecture 4.2 and Lab 3: classes private and public members constructors Destructors, And then go onto streams as an example of a class. CS427 Objects and streams and files 4/18

Recall... The stack example again In Lecture 4.2 and Lab 3, we used a stack (LIFO queue) as an example of an bstract Data Type. Any function in the program can: declare a instance of the class stack. added to the top of the stack: s.push() ; removed from the top of the stack: s.pop(). These are the interfaces to the stack, and are public: For the stack itself, the following must be maintained: a character array contents[] a integer count of the number of items on the stack (top). These are private to the class. CS427 Objects and streams and files 5/18

Constructor We also introduced the idea of constructor. It is a public member function that has the same name as the class It is called automatically when an instance of the class is declared. It cannot have a return type. class stack private: char *contents; int top; public: stack(void); void push(char c); char pop(void ); }; stack::stack(void) top=0; contents = new char[max_stack]; } CS427 Objects and streams and files 6/18

Constructor This is a particularly basic example of a constructor. More commonly we pass arguments to the constructor that can be used Set the value of a data member; Dynamically size an array using new. However, one should still provide a default constructor (i.e., one with no arguments). class stack private: char *contents; int top; public: stack(void); stack(unsigned int StackSize); void push(char c); char pop(void ); }; stack::stack(void) top=0; contents = new char[max_stack]; } stack::stack(unsigned int StackSize) top=0; contents = new char[stacksize]; } CS427 Objects and streams and files 7/18

Destructors Complementing the idea of a constructor is a destructor. This function is called for a local object whenever it goes out of scope for a global object when the program ends. The name of the destructor is the same as the class, but preceded by a tilde: class stack private: char *contents; int top; public: stack(void ); stack(void ); void push(char c); char pop(); }; stack:: stack() delete [] contents; } CS427 Objects and streams and files 8/18

Streams as examples of Objects I/O means Input/Output. So far, we have taken input from the keyboard, typically using cin, and sent output to a terminal window, using cout. These are examples of streams: flows of data to or from your program. Moreover, they are examples of objects in C++. In this section, we ll study how to manipulate these streams in C++, including writing to and reading from files. But first, some more information about cout and cin. CS427 Objects and streams and files 9/18

code, cin methods The objects cout and cin are objects and are manipulated by their methods, i.e., public member functions and operators. Methods: width(int x) minimum number of characters for next output, fill(char x) character used to fill with in the case that the width needs to be elongated to fill the minimum. precision(int x) sets the number of significant digits for floating-point numbers. CS427 Objects and streams and files 10/18

code, cin methods See 01cinANDcout.cpp Code width for (int i=65; i<123; i++) cout.width(8); cout << i; cout.width(3); cout << (char) i; if ( (i%5) == 4) cout << endl; } Output 65 A 66 B 67 C... 70 F 71 G 72 H... 75 K 76 L 77 M... 80 P 81 Q 82 R... 85 U 86 V 87 W 90 Z 91 [ 92 \ 95 _ 96 97 a 100 d 101 e 102 f 105 i 106 j 107 k 110 n 111 o 112 p 115 s 116 t 117 u 120 x 121 y 122 CS427 Objects and streams and files 11/18

code, cin methods Code width, fill cout.fill( 0 ); for (int i=0; i<10000; i+= rand()%2000) cout.width(6); cout << i <<endl; } Output 000000 001383 002269 003046 003961 005754 006089 007475 007967 008616 CS427 Objects and streams and files 12/18

code, cin methods Code precision double Pi=3.1415926535; for (int i=1; i<=10; i++) cout.precision(i); cout << Pi (correct to << i << digits) is << Pi << endl; } Output Pi (correct to 1 digits) is 3 Pi (correct to 2 digits) is 3.1 Pi (correct to 3 digits) is 3.14 Pi (correct to 4 digits) is 3.142 Pi (correct to 5 digits) is 3.1416 Pi (correct to 6 digits) is 3.14159 Pi (correct to 7 digits) is 3.141593 Pi (correct to 8 digits) is 3.1415927 Pi (correct to 9 digits) is 3.14159265 Pi (correct to 10 digits) is 3.141592654 CS427 Objects and streams and files 13/18

code, cin manipulators setw like width left Left justifies output in field width. Used after setw(n). right right justify. endl inserts a newline into the stream and calls flush. flush forces an output stream to write any buffered characters dec changes the output format of number to be in decimal format oct octal format hex hexadecimal format showpoint show the decimal point and some zeros with whole numbers Others: setprecision(n), fixed, scientific, boolalpha, noboolalpha,... Need to include iomanip CS427 Objects and streams and files 14/18

code, cin manipulators All of the C++ programs we have looked at so far took their input from the standard input stream: this was usually the keyboard. Example: cout << Enter an inteter: ; cin >> i; Although, for example, the standard input stream can be redirected to a file, it is usually necessary to open a file from within the program and take the data from there. The same is true for writing to a file. To do either of these takes in C++ we create a file stream and use it just as we would cin or cout. CS427 Objects and streams and files 15/18

Files When working with files, we need to include the fstream header file. To read from a file, declare an object of type ifstream; to write to a file, declare an object of type ofstream. Open the file by calling the open() member function. To read a single character, can use InFile.get ) 1 include iostream > 2 include fstream > 3 include c s t d l i b > 5 using namespace std ; 02CountChars.cpp 7 i n t main ( void ) 8 9 i f s t r e a m I n F i l e ; 10 ofstream OutFile ; 11 char InFileName [ 30]= CPlusPlusTerms. t x t ; 12 char c ; 14 cout Processing the contents of 15 InFileName endl ; 16 cout See Output. t x t f o r more i n f o 17 endl ; 18 I n F i l e. open ( InFileName ) ; 19 OutFile. open ( Output. t x t ) ; 21 i n t i =0; 22 I n F i l e. get ( c ) ; CS427 Objects and streams and files 16/18

Files If there are no more characters left in the input stream, then InFile.eof() evaluates as true. Use the steam objects just as you would use cin or cout: InFile >> data or OutFile << data. Close the files: InFile.close(), OutFile.close() 02CountChars.cpp (continued) 22 while ( I n F i l e. eof ( ) ) 23 24 i ++; 25 I n F i l e. get ( c ) ; 26 } 28 OutFile InFileName contains 29 i characters n ; 32 I n F i l e. close ( ) ; 33 OutFile. close ( ) ; 35 return ( 0 ) ; 36 } CS427 Objects and streams and files 17/18

Files open Note that the method open works differently for ifstream and ofstream; InFile.open Opens an existing file for reading, OutFile.open Opens a file for writing. If it already exists, its contents are overwritten. To open an existing file and append to its contents, use OutFile.open( Output.txt, ios::app); If the open call fails, then the method fail() returns true. So you should always include something like to following after opening a file: if (InFile.fail()) cerr << Error - can t open << InFileName << endl; exit(1); } CS427 Objects and streams and files 18/18