Using Classes Classes and Function Members. Review We’ve seen that the iostream library provides the objects cin, cout and cerr: These objects were not.

Slides:



Advertisements
Similar presentations
Parameter Passing Mechanisms Reference Parameters.
Advertisements

File Operations Functions Manipulating Files. Review The fstream library defines two classes: ifstream, for creating connections between programs and.
Lesson 10 Characters, C-Strings, and the string Class CS1 Lesson John Cole1.
Chapter 10.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Chapter 3: Input/Output
Software Engineering 1 (Chap. 1) Object-Centered Design.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
Using Classes Classes and Function Members — An Introduction to OOP (Object-Oriented Programming) Chapter 7 1 The "++" in C++
Using Classes Classes and Function Members. Review We’ve seen that the iostream library provides the objects cin, cout and cerr: These objects were not.
1 Chapter 10 Characters, Strings, and the string class.
Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.
Using Classes 1 Classes and Function Members — An Introduction to OOP (Object-Oriented Programming) Chapter 7 The "++" in C++
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Working with Strings Lecture 2 Hartmut Kaiser
Controlling Function Behavior Sequence, Selection and Repetition.
Chapter 10. Characters, Strings and the string class Csc 125 Introduction to C++ Fall 2005.
File I/O ifstreams and ofstreams Sections 11.1 &
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Control Structures (B) Topics to cover here: Sequencing in C++ language.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
Characters, Strings, And The string Class Chapter 10.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
CSC 270 – Survey of Programming Languages
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
Chapter 15 Strings as Character Arrays
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
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.
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
Chapter Characters, Strings, and the string class 10.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 8: Namespaces, the class string, and User-Defined Simple Data Types.
Classes and Function Members
Introduction to C++ (Extensions to C)
ifstreams and ofstreams
Characters, C-Strings, and More About the string Class
Writing Reuseable Formulas
solve the following problem...
Standard Version of Starting Out with C++, 4th Edition
Learning Objectives String Class.
10.1 Character Testing.
Chapter 3: Input/Output
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Engineering Problem Solving with C++, Etter
Standard Version of Starting Out with C++, 4th Edition
ifstreams and ofstreams
Std Library of C++.
CS-161 Computer Programming Lecture 15 & 16: Arrays II
Presentation transcript:

Using Classes Classes and Function Members

Review We’ve seen that the iostream library provides the objects cin, cout and cerr: These objects were not originally provided in C++, but were added to the language using its class mechanism.

Classes The C++ class mechanism allows a user to add new types to the language. Bell Labs’ Jerry Schwarz used this to create: an istream class, to define the object cin; andan istream class, to define the object cin; and an ostream class, to define cout and cerr.an ostream class, to define cout and cerr. The resulting I/O system was so elegant, it was incorporated into the language.

Classes (ii) Another class that was added ‘after the fact’ is the string class, which provides a convenient way to store and operate on sequences of characters. The string library provides the type string, plus an assortment of useful string-processing operations.

String Objects Objects of type are indexed variables, meaning that each character in the variable can be accessed via an index or subscript: Objects of type string are indexed variables, meaning that each character in the variable can be accessed via an index or subscript: string name = “John Q. Doe”; Use the subscript operator to access individual chars: oJh nQ. name Do 789 e 10 char firstInitial = name[0]; // firstInitial == ‘J’

Dynamic string Objects name = “Philleas Fogg”; // name.size() == 13 Objects of type can grow and shrink as necessary to store their contents: Objects of type string can grow and shrink as necessary to store their contents: oJh nQ. name Do 789 e 10 hPillea name s F 789 o 10 g 11 g 12 string name = “John Q. Doe”; // name.size() == 11

7 string I/O The string class has > operatorsThe string class has > operators –Can do I/O directly with string objects string name, prompt = "Enter name : "; cout > name; string input and whitespacestring input and whitespace –Skips leading whitespace characters –Quits reading when whitespace encountered

8 Other string Operations Subscript operationSubscript operation –Access individual characters of a string string name = "John Doe"; cout << name [2]; Size methodSize method –Determine number of characters in the string cout << name.size(); Empty methodEmpty method –Returns true if string is empty 8 characters

9 Other string Operations Assignment operatorAssignment operator –Assign values to string objects string yesterday, today = "Monday"; yesterday = today; today = "Tuesday"; Relational operatorRelational operator –Elements of string operands compared character by character

10 Other string Operations ConcatenationConcatenation –Combining two strings into a single string string state = "Michigan", greatLake; greatLake = "Lake "+state; The substr(first, num_chars) methodThe substr(first, num_chars) method –Returns a string from first for num_chars cout << greatLake.substr(2,4); What gets printed?

11 Other string Operations The replace(first, num_chars, replace) methodThe replace(first, num_chars, replace) method –Replaces the contents of the replace string starting at first, for num_chars –Given –What is the end result of fullname.replace(5,6,"Eyre"); Six characters replaced with four. ohnD

12 Other string Operations The insert(position, new_string) methodThe insert(position, new_string) method –Inserts a substring into a string –Given –What is the result of signature.insert (5,"E. ");

13 Other string Operations The find(pattern, position) and rfind(pattern, position) methodsThe find(pattern, position) and rfind(pattern, position) methods –These do pattern matching –Searches for the specified pattern starting at the given position –Returns the index of where it is found (returns value of string::npos if not found) –rfind searches from right to left The find_first_of(pattern, position) methodThe find_first_of(pattern, position) method –Looks for first character from any in pattern starting at position

Some string Operations Operation string function read a word from an istream istream >> str; find the length of the string str.size() find if a string is empty str.empty() access the char at index i str[i] concatenate two strings str1 + str2 access a substring of a string str.substr(Pos, NumChars) insert a substring into a string str.insert(Pos, SubStr); remove a substring str.erase(Pos, NumChars); find a substring in a string str.find(Pattern, StartPos) compare two strings str1 == str2 (or !=,, =) (or !=,, =)...//example: ex4-1.cpp

Discussion Some string operations are “normal” functions: getline(cin, aString); Other string operations are function members: aString.size(); Function members are “messages” that class objects “understand” and to which they respond... For example, “knows” how big it is, so when it receives the message, it responds with the appropriate answer. For example, aString “knows” how big it is, so when it receives the size() message, it responds with the appropriate answer.

Function Members Where a “normal” function is an external agent that acts upon an object, a function member is a message that elicits an internal response from the object receiving it. Examples: getline(cin, aString); // getline() acts on aString if (aString.empty()) // ask aString, “are you empty?” if (cin.good()) // ask cin, “are you good?” In this sense, class objects are “more intelligent” than regular char, int, double,... objects.

Classes Most classes provide a rich set of operations that can be used to manipulate objects of the class. To use a class effectively, you must know what kinds of functions (“normal” and member) are available to operate on objects of that class. Otherwise, you risk spending much of your time “reinventing the wheel.”

Other Classes As mentioned earlier, cin and cout are objects of the istream and ostream classes, respectively. To use these classes effectively, you must be aware of the range operations available for them...

19 Difficulty Sometimes, one needs to manipulate a string differently from any of the provided methods. Example: Suppose a problem requires that every uppercase character in a string be converted to its lowercase equivalent. Solution: Write a function to perform the operation!

20 Behavior Our function should receive from its caller a string. It should make a copy of this string to process. It should then examine each character in the copy: if a character is uppercase, it should be converted to lowercase. Our function should return the resulting copy of the string.

21 Objects Description Type Kind Name a char of aString char varying aString[i] the copy string varying result a string string varying aString

22 Operations Description Predefined? Library? Name receive a string yes built-in -- copy a string yes string = examine a char yes string [] of a string repeat this step yes built-in for for each char is a char UC? yes cstring isupper() convert char to LC yes cstring tolower() return a string yes built-in return

23 Algorithm 0. Receive aString from caller. 1. Copy aString into result. 2. For each index i in result: If result[i] is uppercase: If result[i] is uppercase: Replace result[i] with its lowercase equivalent. Replace result[i] with its lowercase equivalent. 3. Return result.

24 Coding /* ToLower() string conversion * Receive: aString, a string. * Return: result, a copy of aString in lowercase. */ #include // isupper(), tolower() using namespace std; string ToLower(string aString) { string result = aString; for (int i = 0; i < result.size(); i++) if (isupper(result[i])) result[i] = tolower(result[i]); return result; }

25 Organization This function seems likely to be reusable someday, so we store it in a library: its prototype in a header file;its prototype in a header file; its definition in an implementation file; andits definition in an implementation file; and its prototype and supporting documentation in a documentation file.its prototype and supporting documentation in a documentation file. We then write a test program...

26 Driver #include // cin, cout #include // string using namespace std; #include “StringOps.h” // ToLower() int main() { cout << “\nEnter a string with uppercase letters:\n“; string stringIn; getline(cin, stringIn); string stringOut = ToLower(stringIn); cout << “\nThe converted string is:\n“ << stringOut << endl; }

27 Library Maintenance Once we are certain our function’s logic is correct, it makes sense to define a symmetric function ToUpper() for our library, using similar logic: string ToUpper(string aString) { string result = aString; for (int i = 0; i < result.size(); i++) if (islower(result[i])) result[i] = toupper(result[i]); return result; }

28 Summary Well-designed classes provide a rich set of operations that make them useful for many problems. Operations can be external (normal functions), or internal (function members) to the class. Function members act as messages to class objects. To use a class effectively, you must know what capabilities the class provides; andwhat capabilities the class provides; and how to use those capabilities.how to use those capabilities.

29 Summary Class libraries generally provide a rich set of predefined operations.Class libraries generally provide a rich set of predefined operations. When a problem requires an operation that is not predefined, a function to perform the operation can usually be defined by using the provided operations in whatever combination is appropriate for solving the problem.When a problem requires an operation that is not predefined, a function to perform the operation can usually be defined by using the provided operations in whatever combination is appropriate for solving the problem.