11 Introduction to Object Oriented Programming (Continued) Cats II.

Slides:



Advertisements
Similar presentations
Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
Advertisements

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.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
Writing a Good Program 6. Pointers and Arrays
Chapter 10.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 9/1/06CS150 Introduction to Computer Science 1 What Data Do We Have? CS 150 Introduction to Computer Science I.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
CS161 Topic #14 1 Today in CS161 Lecture #14 Practicing! Writing Programs to Practice Write a program that counts the number of vowels in a sentence, ended.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
February 11, 2005 More Pointers Dynamic Memory Allocation.
1 C++ Programming Basics Chapter 2 Lecture CSIS 10A.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
CHAPTER 7 DATA INPUT OUTPUT Prepared by: Lec. Ghader R. Kurdi.
1 CS161 Introduction to Computer Science Topic #3.
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Hank Childs, University of Oregon May 13th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
C++ Memory Overview 4 major memory segments Key differences from Java
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Chapter 05 (Part III) Control Statements: Part II.
CS Class 05 Topics  Selection: switch statement Announcements  Read pages 74-83, ,
11 Introduction to Object Oriented Programming (Continued) Cats.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
1 Workin’ with Pointas An exercise in destroying your computer.
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.
1 Program Input Software Design Chapter 4. 2 You Will Want to Know... Prompting for and reading values into a program. Accessing data from a file. What.
Overview of c++ Objectives 1. Understanding the use of the following elements in a c++ program variables constants assignment input output 2. Writing a.
1 Derived Classes Chapter Objectives You will be able to: Create and use derived classes.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
1 Getting Started with C++ Part 2 Linux. 2 Getting Started on Linux Now we will look at Linux. See how to copy files between Windows and Linux Compile.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 Introduction to Object Oriented Programming Chapter 10.
1 Derived Classes Chapter Objectives You will be able to: Create and use derived classes. Understand the meaning of polymorphism and how it works.
Fundamental Programming Fundamental Programming Introduction to Functions.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
1 Huffman Codes Using Binary Files. 2 Getting Started Last class we extended a program to create a Huffman code and permit the user to encode and decode.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Why exception handling in C++?
Introduction to C++ October 2, 2017.
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
Today in CS161 Week #3 Learn about… Writing our First Program
CS150 Introduction to Computer Science 1
Introduction to Programming
Reading from and Writing to Files
Today’s Objectives 28-Jun-2006 Announcements
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 1 c++ structure C++ Input / Output
Reading from and Writing to Files Part 2
Reading from and Writing to Files
Presentation transcript:

11 Introduction to Object Oriented Programming (Continued) Cats II

22 Objectives You will be able to: Create objects dynamically. Use dynamically created objects in a C++ program. Get keyboard input from a user in a C++ program.

33 Get the Cats Program If you don’t have the Cats program from last class on your computer, you can download it from the class web site: _01_19_Cats/ _01_19_Cats/

44 Dynamic Allocation We can dynamically create objects of any class using new. Similar to malloc in C. Allocates space on the heap. Invokes constructor to initialize the object. Returns a pointer to the object.

55 Dynamic Allocation #include #include "Cat.h" using namespace std; int main() { cout << "This is program Cats\n"; Date dob = {12,1,2008}; Cat* Fluffy = new Cat("Fluffy", dob, 8.4); Fluffy->Display(); cout << endl; cin.get(); // Hold window open. return 0; } Note arrow. Fluffy is now a pointer.

66 Object Lifetime Objects allocated by declaration are deallocated when the function exits. Like all local variables. Objects allocated with new continue to exist until explicitly deleted. delete c1; c1 is a pointer to the object that is to be deleted.

77 Explicitly Deleting an Object #include #include "Cat.h" using namespace std; int main() { cout << "This is program Cats\n"; Date dob = {12,1,2008}; Cat* Fluffy = new Cat("Fluffy", dob, 8.4); Fluffy->Display(); cout << endl; delete Fluffy; Fluffy = 0; cin.get(); // Hold window open. return 0; }

88 Getting User Input What if we want the user to specify the attributes of a Cat. Could overload the constructor and provide a version that asks for input. Better to provide a separate function outside the class definition. Separate UI from class logic. Let’s write a function that asks the user for information about a Cat, creates a Cat object, and returns a pointer to the object.

99 main.cpp Cat* Create_Cat() { char name[21]; Date date_of_birth; double weight; cout << "Please enter information for new Cat\n"; cout << "Name (up to 20 characters): "; cin.getline(name, 20); cout << "Date of Birth:\n"; cout << " Month: "; cin >> date_of_birth.Month; cout << " Day: "; cin >> date_of_birth.Day; cout << " Year: "; cin >> date_of_birth.Year; cout << "Weight: "; cin >> weight; Cat* cat = new Cat(name, date_of_birth, weight); return cat; }

10 Getting User Input int main() { cout << "This is program Cats\n"; Cat* cat1 = Create_Cat(); cat1->Display(); cout << endl; delete cat1; cat1 = 0; cin.get(); // Hold window open. cin.get(); return 0; } In file main.cpp

11 Running Program Cats

12 Running Program Cats

13 Problems with String Input C++ String input is tricky! What happens if the user inputs more than 20 characters for the cat's name? Try it! Use Debug > Start without Debugging Or Ctrl+F5

14 Avoiding the Problem Read into a large buffer array. Operating system will limit input to some reasonable amount. (~255 characters) Copy up the the max number of characters into the real input array. If the user enters too many characters? Output an error message and ask the user to try again. or Just ignore the excess input.

15 Function Get_String() void Get_String(char* prompt, char* input_array, size_t max_chars) { char input_buffer[1000]; while (true) { cout << prompt; cin.getline(input_buffer, 1000); if (strlen(input_buffer) <= max_chars) { break; } cout << "Please enter no more than " << max_chars << " characters\n"; } strcpy(input_array, input_buffer); }

16 Using Get_String() Cat* Create_Cat() { char name[21]; Date date_of_birth; double weight; cout << "Please enter information for new Cat\n"; Get_String("Name (up to 20 characters): ", name, 20); cout << "Date of Birth:\n";...

17 Program Running

18 Long Input String Exactly 20 characters

19 Multiple Cats int main() { cout << "This is program Cats\n"; while (true) { Cat* cat1 = Create_Cat(); cat1->Display(); cout << endl; delete cat1; cat1 = 0; }...

20 Program Running Whoa! What happened here?

21 A Problem with cin >> cin >> weight; User enters 8.4 (followed by "Enter") The >> operator extracts "8.4" from the keyboard input buffer. Leaves the newline character. Next input sees the newline character as the first thing in the buffer. No problem when next input is for a numeric value. Big problem when next input is for a string.

22 A Related Problem The final "." in input "8.4." was left in the keyboard input buffer and read as name of the next cat.

23 Solution After numeric input, clear the newline character (and potential garbage) from the keyboard input buffer before doing the next real input. while (cin.get() != '\n') ; Do nothing

24 Clear_Keyboard_Input_Buffer() void Clear_Keyboard_Input_Buffer() { while (cin.get() != '\n') ; } Call this function after getting a numeric value to clear the newline character following the numeric text. Also handles the problem when the user enters nonnumeric text after the numeric value.

25 Using Clear_Keyboard_Input_Buffer Cat* Create_Cat() {... cout << "Date of Birth:\n"; cout << " Month: "; cin >> date_of_birth.Month; cout << " Day: "; cin >> date_of_birth.Day; cout << " Year: "; cin >> date_of_birth.Year; cout << "Weight: "; cin >> weight; Clear_Keyboard_Input_Buffer(); Cat* cat = new Cat(name, date_of_birth, weight); return cat; }

26 Program in Action Garbage at end of numeric inputs was silently ignored.

27 Assignment Do today's examples for yourself if you have not done them in class. Read Chapter 10. Project 1 End of Presentation