Fundamentals of Programming Session 25

Similar documents
Fundamentals of Programming Session 27

IS 0020 Program Design and Software Tools

Lecture 9. Introduction

Chapter 8 File Processing

Functions and Recursion

Fundamentals of Programming Session 28

Chapter 3 - Functions

Chapter 3 - Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

C++ Programming Lecture 10 File Processing

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

IS 0020 Program Design and Software Tools

6.5 Function Prototypes and Argument Coercion

EAS230: Programming for Engineers Lab 1 Fall 2004

C Functions. 5.2 Program Modules in C

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

Chapter 14 File Processing

Introduction to Programming

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Introduction to Programming

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

PIC10B/1 Winter 2014 Exam I Study Guide

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

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 12 - C++ Stream Input/Output

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

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CSE123. Program Design and Modular Programming Functions 1-1

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Chapter 2 - Control Structures

BITG 1113: Files and Stream LECTURE 10

Chapter 3 - Functions

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

Introduction to C++ Systems Programming

IS 0020 Program Design and Software Tools

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Operator Overloading in C++ Systems Programming

Advanced I/O Concepts

Fundamentals of Programming Session 24

Input and Output File (Files and Stream )

Function Call Stack and Activation Records

Chapter 14 Sequential Access Files

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

CS201 Solved MCQs.

Arrays. Week 4. Assylbek Jumagaliyev

Chapter 2 - Control Structures

Chapter 2 - Control Structures

Fall 2017 CISC/CMPE320 9/27/2017

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

A Deeper Look at Classes

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

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

Pointers and Strings Prentice Hall, Inc. All rights reserved.

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

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

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Objects and streams and files CS427: Elements of Software Engineering

57:017, Computers in Engineering C++ Classes

Introduction to Programming session 24

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

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Chapter 18 - C++ Operator Overloading

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

Lecture 5 Files and Streams

System Design and Programming II

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

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 2 - Control Structures

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

10/23/02 21:20:33 IO_Examples

The Hong Kong Polytechnic University Faculty of Engineering

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

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

Week 5: Files and Streams

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

CS201 Latest Solved MCQs

Introduction. Lecture 5 Files and Streams FILE * FILE *

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

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

More C++ Classes. Systems Programming

Chapter 12. Streams and File I/O

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

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

Streams. Rupesh Nasre.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

C++ Input/Output: Streams

Transcription:

Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology

Outlines Default Memberwise Assignment Union Introducing enum File Processing Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File 2

Default Memberwise Assignment 3 Assigning objects Assignment operator (=) Can assign one object to another of same type Default: memberwise assignment Each right member assigned individually to left member Passing, returning objects Objects passed as function arguments Objects returned from functions Default: pass-by-value Copy of object passed, returned Copy constructor o Copy original values into new object

4 1 // Demonstrating that class objects can be assigned 2 // to each other using default memberwise assignment. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // class Date definition 7 class Date { 8 public: 9 Date( int = 1, int = 1, int = 1990 ); // default constructor 10 void print(); 11 private: 12 int month; 13 int day; 14 int year; 15 }; // end class Date

5 16 // Date constructor with no range checking 17 Date::Date( int m, int d, int y ) 18 { 19 month = m; 20 day = d; 21 year = y; 22 } // end Date constructor 23 // print Date in the format mm-dd-yyyy 24 void Date::print() 25 { 26 cout << month << '-' << day << '-' << year; 27 } // end function print 28 int main() 29 { 30 Date date1( 7, 4, 2002 ); 31 Date date2; // date2 defaults to 1/1/1990

32 cout << "date1 = "; 33 date1.print(); 34 cout << "\ndate2 = "; 35 date2.print(); 36 date2 = date1; // default memberwise assignment 37 cout << "\n\nafter default memberwise assignment, date2 = "; 38 date2.print(); 39 cout << endl; 40 return 0; 41 } // end main date1 = 7-4-2002 date2 = 1-1-1990 After default memberwise assignment, date2 = 7-4-2002 6

Union Union Memory that contains a variety of objects Data members share space Only contains one data member at a time Only the last data member defined can be accessed Declaration same as class or struct union Number { }; int x; float y; Union myobject; 7

8 1 // Fig. 20.8: fig20_08.cpp 2 // An example of a union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // define union Number 7 union Number { 8 int integer1; 9 double double1; 10 }; // end union Number 11 int main() 12 { 13 Number value; // union variable 14 value.integer1 = 100; // assign 100 to member integer1 15 cout << "Put a value in the integer member\n" 16 << "and print both members.\nint: " 17 << value.integer1 << "\ndouble: " << value.double1 18 << endl;

19 value.double1 = 100.0; // assign 100.0 to member double1 20 cout << "Put a value in the floating member\n" 21 << "and print both members.\nint: " 22 << value.integer1 << "\ndouble: " << value.double1 23 << endl; 24 return 0; 25 } // end main 9 Put a value in the integer member and print both members. int: 100 double: -9.25596e+061 Put a value in the floating member and print both members. int: 0 double: 100

10 1 // Fig. 20.9: fig20_09.cpp 2 // Using an anonymous union. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 int main() 7 { 8 // declare an anonymous union 9 // members integer1, double1 and charptr share the same space 10 union { 11 int integer1; 12 double double1; 13 char *charptr; 14 }; // end anonymous union 15 // declare local variables 16 int integer2 = 1; 17 double double2 = 3.3; 18 char *char2ptr = "Anonymous";

19 // assign value to each union member 20 // successively and print each 21 cout << integer2 << ' '; 22 integer1 = 2; 23 cout << integer1 << endl; 24 25 cout << double2 << ' '; 26 double1 = 4.4; 27 cout << double1 << endl; 28 29 cout << char2ptr << ' '; 30 charptr = "union"; 31 cout << charptr << endl; 32 return 0; 33 } // end main 11 1 2 3.3 4.4 Anonymous union

Introducing enum Enumeration Set of integers with identifiers enum typename {constant1, constant2 }; Constants start at 0 (default), incremented by 1 Constants need unique names Cannot assign integer to enumeration variable Must use a previously defined enumeration type Example enum Status {CONTINUE, WON, LOST}; Status enumvar; enumvar = WON; // cannot do enumvar = 1 12

Introducing enum 13 Enumeration constants can have preset values enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Starts at 1, increments by 1 Next: craps simulator Roll two dice 7 or 11 on first throw: player wins 2, 3, or 12 on first throw: player loses 4, 5, 6, 8, 9, 10 Value becomes player's "point" Player must roll his point before rolling 7 to win

14 1 // Fig. 3.10: fig03_10.cpp 2 // Craps. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // contains function prototypes for functions srand and rand 7 #include <cstdlib> 8 #include <ctime> // contains prototype for function time 9 int rolldice( void ); // function prototype 10 int main() 11 { 12 // enumeration constants represent game status 13 enum Status { CONTINUE, WON, LOST }; 14 int sum; 15 int mypoint; 16 Status gamestatus; // can contain CONTINUE, WON or LOST

15 17 // randomize random number generator using current time 18 srand( time( 0 ) ); 19 sum = rolldice(); // first roll of the dice 20 // determine game status and point based on sum of dice 21 switch ( sum ) { 22 // win on first roll 23 case 7: 24 case 11: 25 gamestatus = WON; 26 break; 27 // lose on first roll 28 case 2: 29 case 3: 30 case 12: 31 gamestatus = LOST; 32 break;

16 33 // remember point 34 default: 35 gamestatus = CONTINUE; 36 mypoint = sum; 37 cout << "Point is " << mypoint << endl; 38 break; // optional 39 } // end switch 40 // while game not complete... 41 while ( gamestatus == CONTINUE ) { 42 sum = rolldice(); // roll dice again 43 // determine game status 44 if ( sum == mypoint ) // win by making point 45 gamestatus = WON; 46 else 47 if ( sum == 7 ) // lose by rolling 7 48 gamestatus = LOST; 49 } // end while

17 50 // display won or lost message 51 if ( gamestatus == WON ) 52 cout << "Player wins" << endl; 53 else 54 cout << "Player loses" << endl; 55 return 0; // indicates successful termination 56 } // end main 57 // roll dice, calculate sum and display results 58 int rolldice( void ) 59 { 60 int die1; 61 int die2; 62 int worksum; 63 die1 = 1 + rand() % 6; // pick random die1 value 64 die2 = 1 + rand() % 6; // pick random die2 value 65 worksum = die1 + die2; // sum die1 and die2

66 // display results of this roll 67 cout << "Player rolled " << die1 << " + " << die2 68 << " = " << worksum << endl; 69 return worksum; // return sum of dice 70 } // end function rolldice Player rolled 2 + 5 = 7 Player wins Player rolled 6 + 6 = 12 Player loses Player rolled 3 + 3 = 6 Point is 6 Player rolled 5 + 3 = 8 Player rolled 4 + 5 = 9 Player rolled 2 + 1 = 3 Player rolled 1 + 5 = 6 Player wins 18

Player rolled 1 + 3 = 4 Point is 4 Player rolled 4 + 6 = 10 Player rolled 2 + 4 = 6 Player rolled 6 + 4 = 10 Player rolled 2 + 3 = 5 Player rolled 2 + 4 = 6 Player rolled 1 + 1 = 2 Player rolled 4 + 4 = 8 Player rolled 4 + 3 = 7 Player loses 19

File Processing Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical disk, tapes 20

Data Hierarchy From smallest to largest Bit (binary digit) 1 or 0 Everything in computer ultimately represented as bits Cumbersome for humans to use Character set Digits, letters, symbols used to represent data Every character represented by 1's and 0's Byte: 8 bits Can store a character (char) 21

Data Hierarchy From smallest to largest (continued) Field: group of characters with some meaning Your name Record: group of related fields struct or class in C++ Each field associated with same employee Record key: field used to uniquely identify record File: group of related records Sequential file: records stored by key Database: group of related files 22

Data Hierarchy Sally Tom Judy Iris Randy Black Blue Green Orange Red File Judy Judy 01001010 Green Field Byte (ASCII character J) Record 1 Bit 23

Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker 0 1 2 3 4 5 6 7 8 9... n-1... end-of-file marker When file opened Object created, stream associated with it cin, cout, etc. created when <iostream> included Communication between program and file/device 24

Files and Streams To perform file processing Include <iostream> and <fstream> Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) 25

Creating a Sequential-Access File C++ imposes no structure on file Concept of "record" must be implemented by programmer To open file, create objects Classes ifstream (input only) ofstream (output only) fstream (I/O) Constructors take file name and file-open mode ofstream outclientfile( "filename", fileopenmode ); To attach a file later Ofstream outclientfile; outclientfile.open( "filename", fileopenmode); 26

Creating a Sequential-Access File File-open modes Mode ios::app ios::in ios::out ios::binary Description Write all output to the end of the file. Open a file for input. Open a file for output. Open a file for binary (i.e., non-text) input or output. ofstream opened for output by default ofstream outclientfile( "clients.dat", ios::out ); ofstream outclientfile( "clients.dat"); 27

Creating a Sequential-Access File Operations Overloaded operator!!outclientfile Returns nonzero (true) if badbit or failbit set Opened non-existent file for reading, wrong permissions Operations Writing to file (just like cout) outclientfile << myvariable Closing file outclientfile.close() Automatically closed when destructor called 28

29 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 #include <fstream> 8 using std::ofstream; 9 #include <cstdlib> // exit prototype 10 int main() 11 { 12 // ofstream constructor opens file 13 ofstream outclientfile( "clients.dat", ios::out ); 14 // exit program if unable to create file 15 if (!outclientfile ) { // overloaded! operator 16 cerr << "File could not be opened" << endl; 17 exit( 1 ); 18 } // end if

30 19 cout << "Enter the account, name, and balance." << endl 20 << "Enter end-of-file to end input.\n? "; 21 int account; 22 char name[ 30 ]; 23 double balance; 24 // read account, name and balance from cin, then place in file 25 while ( cin >> account >> name >> balance ) { 26 outclientfile << account << ' ' << name << ' ' << balance 27 << endl; 28 cout << "? "; 29 } // end while 30 return 0; // ofstream destructor closes file 31 } // end main

Enter the account, name, and balance. Enter end-of-file to end input.? 100 Jones 24.98? 200 Doe 345.67? 300 White 0.00? 400 Stone -42.16? 500 Rich 224.62? ^Z 31

Reading Data from a Sequential-Access File Reading files ifstream inclientfile( "filename", ios::in ); Overloaded!!inClientFile tests if file was opened properly while (inclientfile >> myvariable) Stops when EOF found (gets value 0) 32

33 1 #include <iostream> 2 using std::cout; 3 using std::cin; 4 using std::ios; 5 using std::cerr; 6 using std::endl; 7 using std::left; 8 using std::right; 9 using std::fixed; 10 using std::showpoint; 11 #include <fstream> 12 using std::ifstream; 13 #include <iomanip> 14 using std::setw; 15 using std::setprecision; 16 #include <cstdlib> // exit prototype 17 void outputline( int, const char * const, double );

34 18 int main() 19 { 20 // ifstream constructor opens the file 21 ifstream inclientfile( "clients.dat", ios::in ); 22 // exit program if ifstream could not open file 23 if (!inclientfile ) { 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); 26 } // end if 27 int account; 28 char name[ 30 ]; 29 double balance; 30 cout << left << setw( 10 ) << "Account" << setw( 13 ) 31 << "Name" << "Balance" << endl << fixed << showpoint; 32 // display each record in file 33 while ( inclientfile >> account >> name >> balance ) 34 outputline( account, name, balance ); 35 return 0; // ifstream destructor closes the file 36 } // end main

37 // display single record from file 38 void outputline( int account, const char * const name, 39 double balance ) 40 { 41 cout << left << setw( 10 ) << account << setw( 13 ) << name 42 << setw( 7 ) << setprecision( 2 ) << right << balance 43 << endl; 44 45 } // end function outputline Account Name Balance 100 Jones 24.98 200 Doe 345.67 300 White 0.00 400 Stone -42.16 500 Rich 224.62 35