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
More Review, with Some New Chapter 3. Review C++ simple data types – Integral and float – Arithmetic operators Expressions and expression evaluation –
Advertisements

CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
1 Lecture 5: Input/Output (I) Introduction to Computer Science Spring 2006.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
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
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Using Classes Classes and Function Members — An Introduction to OOP (Object-Oriented Programming) Chapter 7 1 The "++" in C++
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++
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.
CHAPTER 3 INPUT/OUTPUT. In this chapter, you will:  Learn what a stream is and examine input and output streams  Explore how to read data from the standard.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 3: Input/Output.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
C++ Streams Lecture-2.
File I/O ifstreams and ofstreams Sections 11.1 &
File I/O ifstreams and ofstreams. Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store.
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
Chapter 3: Input/Output
1 Character Strings (Cstrings) Reference: CS215 textbook pages
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
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
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.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Math Operators and Output Formatting. Incrementing and Decrementing StatementEquivalent Counter++;Counter = Counter + 1; ++Counter;Counter = Counter +
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
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.
Bill Tucker Austin Community College COSC 1315
Classes and Function Members
Topic 2 Input/Output.
Introduction to C++ (Extensions to C)
ifstreams and ofstreams
EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.
Basic Input and Output Operations
Chapter 2 part #3 C++ Input / Output
Standard Input/Output Streams
Standard Input/Output Streams
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3: Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 2 part #3 C++ Input / Output
ifstreams and ofstreams
Chapter 1 c++ structure C++ Input / Output
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

Some string Operations Operation string function read a word from an istream istream >> str; read a line from an istream getline(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.remove(Pos, NumChars); find a substring in a string str.find(Pattern, StartPos) compare two strings str1 == str2 (or !=,, =) (or !=,, =)...

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.”

Example Suppose a problem requires me to find the position of a particular character within a string. I can either write/call my own function to do so... int PositionOf(char ch; string str) { for (int i = 0; i < str.size(); i++) if (str[i] == ch) return i; return -1; }... int pos = PositionOf(myChar, aString);

Example (ii)... or I can ask aString to locate myChar for me, using the string function member named find(): int pos = aString.find(myChar, 0); Which is less work? Writing your own is more work to code, test and debug, and the result is less flexible than find().Writing your own is more work to code, test and debug, and the result is less flexible than find(). Using find() requires awareness (i) that the function member exists, and (ii) of how to use it.Using find() requires awareness (i) that the function member exists, and (ii) of how to use it.

Discussion Be aware of the functionality a class provides (but don’t memorize the nitty-gritty details). Know where (in a reference book) to look up the operations a class supports. Then, when a problem involves an operation on a class object, scan the list of operations looking for one that you can use -- don’t reinvent the wheel!

Example The text provides a RandomInt class. Objects of this class are integers with “random” values, which can be used to simulate all sorts of “random” occurrences. #include “RandomInt.h”... RandomInt die1(1,6), die2(1,6); // two dice die1.Generate(); die2.Generate() // roll the dice cout << “dice roll = “ // display results << die1 + die2 << endl;

RandomInt Objects The range of random values is specified when an object is declared: #include “RandomInt.h”... const int HEADS = 0, TAILS = 1; RandomInt coin(HEADS,TAILS); coin.Generate(); // flip coin cout << coin << endl; // display result

RandomInt Operations Operation RandomInt function Display a RandomInt ostream << randInt Declare a RandomInt RandomInt name; Declare a RandomInt within range first..last RandomInt name(first, last); Generate new random value randInt.Generate(); Generate new random value from range first..last randInt.Generate(first, last); Add two RandomInt values randInt1 + randInt2 (also -, *, /) Compare two RandomInt values randInt1 == randInt2 (also !=,, =)

Sample Program #include // cin, cout using namespace std; // RandomInt class #include “RandomInt.h” // RandomInt class int main() { const int HEADS = 0, TAILS = 1; // for readability const int HEADS = 0, TAILS = 1; // for readability // model a coin RandomInt coin(HEADS, TAILS); // model a coin int numHeads = 0, numTails = 0; // counters int numHeads = 0, numTails = 0; // counters for (int i = 1; i <= 10000; i++) // loop 10,000 times for (int i = 1; i <= 10000; i++) // loop 10,000 times { // flip coin coin.Generate(); // flip coin if () // count if (coin == HEADS) // count numHeads++; // heads numHeads++; // heads else // vs. tails else // vs. tails numTails++; numTails++; } cout << “\nIn 10,000 tosses of a coin,\n” cout << “\nIn 10,000 tosses of a coin,\n” << “ heads occurred “ << numHeads << “ times\n” << “ heads occurred “ << numHeads << “ times\n” << “ and tails occurred << numTails << “ times” << “ and tails occurred << numTails << “ times” << endl; << endl;}

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...

Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store it in ch. from cin and store it in ch. cin.get(ch); Tell cin, “Put your next character (whitespace or not) into ch.” (whitespace or not) into ch.” cin.good() Ask cin, “Are you in good shape?” cin.bad() Ask cin, “Is something wrong?" cin.fail() Ask cin, “Did the last operation fail?” cin.clear(); Tell cin, “Reset yourself to be good.” cin.ignore(n, ch); Tell cin, ignore the next n characters, or until ch occurs, whichever comes first. or until ch occurs, whichever comes first.

Some ostream Operations ostream function Description cout >> expr Insert expr into cout. cout.put(ch); Tell cin, “Insert ch into yourself.” cout << flush Write contents of cout to screen. cout << endl Write a newline to cout and flush it. cout << fixed Display reals in fixed-point notation. cout << scientific Display reals in scientific notation. cout << showpoint Display decimal point and trailing zeros for real whole numbers. for real whole numbers. cout << noshowpoint Hide decimal point and trailing zeros for real whole numbers. for real whole numbers.

More ostream Operations ostream function Description cout << showpos Display sign for positive values. cout << noshowpos Hide sign for positive values. cout << boolalpha Display true, false as “true”, “false”. cout << noboolalpha Display true, false as 1, 0. cout << setprecision(n) Display n decimal places for reals. cout << setw(w) Display next value in field width w. cout << left Left-justify subsequent values. cout << right Right-justify subsequent values. cout << setfill(ch) Fill leading/trailing blanks with ch.

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.