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.

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Classes and Data Abstraction Lecture 9. Objects Models of things in the real world Defined in classes  Class name is the object name Example: Library.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 10.
Today’s Class Class string –The basics –Assignment –Concatenation –Compare & swap –Find –Conversion to C-style char * strings –Iterators.
1 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
11 Introduction to Object Oriented Programming (Continued) Cats II.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
Working with Strings Lecture 2 Hartmut Kaiser
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Pointers OVERVIEW.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Dynamic memory allocation and Pointers Lecture 4.
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.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CS31: Introduction to Computer Science I Discussion 1A 5/14/2010 Sungwon Yang
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
11 Introduction to Object Oriented Programming (Continued) Cats.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Working with Strings Lecture 2 Hartmut Kaiser
Copyright © 2003 Pearson Education, Inc.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 15 Pointers, Dynamic Data, and Reference Types
Class string and String Stream Processing
CS150 Introduction to Computer Science 1
Dynamic Memory.
Std Library of C++.
Chapter 1 c++ structure C++ Input / Output
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 any other class –string str; Notice string is lower case = operator is overloaded so you can set strings –str = “Hello World”; Can also be initialized as it is declared –string str = “Hello World”; –Or std::string str = “Hello World”;

Has Friend functions You can use cin and cout with strings – > are friends of the class #include #include using namespace std; int main() { string s; cin >> s; cout << s << endl; }

Useful Operators + allows you to concatenate strings –string s1 = “Hello “ ; –string s2 = “ World”; –string s3 = s1 + s2; // s3 now has “Hello World” += Short cut for concatenating –s1+= s2;

Equality Operators Produce true or false values string s1 = “Hello”; string s2 = “World”; s1 == s2 ; // produces false s1 != s2 ; // produces true s1 > s2; // produces false because W is greater in ascii than H s1 < s2; // produces true for the same reason as above Also have <= less than or equal >= greater than or equal

Can be treated like an array The subscript operator can be used to return a character string str = “ABC”; char c = str[1]; // c now holds B Can also set a character string str = “ABC”; str[1] = ‘Z’; // str now has AZC Be careful setting characters Make sure the string has some space first string str; str[1] = ‘x’; // Not a good idea str = “Hello”; str[1] = ‘a’; // works ok str now holds hallo

Useful Member Functions length() & size () functions –Both return the number of characters string str = "Hello"; cout << str.size() << endl; // both output 5 cout << str.length() << endl; c_str() returns a null terminated array of chars A c string! Useful for older library functions that don’t know what a string is erase(int start, int length); string str = "abcdefghi"; str.erase (5,3); cout << str12 << endl; // yields "abcdei"

find & rfind find(string &find, size_t pos) searches for the first occurrence of a string starting at pos. Returns the position of the 1 st character of the found string string s = “abcdefghi” string s1 = “def”; int pos = s.find(s1, 0); // returns the position of d in the string 3 in this case rfind does the same as find except that it finds the last occurrence

substr functions substr(int pos, int length) Returns a substring of the current string starting at pos with the specified length string str = “abcdefghi”; string str1 = str.substr(6, 2); // str1 now holds “gh”

The getline function getline(istream &is, string &str, char delim = ‘\n’); Reads characters from an input stream into a string, stopping when one of the following things happens: –An end-of-file condition occurs on the input stream –When the maximum number of characters that can fit into a string have been read –When a character read in from the string is equal to the specified delimiter (newline is the default delimiter); the delimiter character is removed from the input stream, but not appended to the string.

More getline Returns a reference to the input stream. –If the stream is tested as a logical value (as in an if or while), it is equivalent to true if the read was successful and false otherwise (e.g., end of file). The most common use of this function is to do "line by line" reads from a file. Remember that the normal extraction operator (>>) stops on white space, not necessarily the end of an input line.extraction operator The getline function can read lines of text with embedded spaces.

getline example #include using namespace std; Int main() { vector vec1; string line; vec1.clear(); ifstream infile ("stl2in.txt"); while (getline(infile,line,'\n')) { vec1.push_back (line); }

Dynamic memory allocation Until now, in our programs, we have only had as much memory as we have requested in declarations of variables –Array sizes have been fixed Not good because data in programs can grow and shrink as they run How do we dynamically allocate memory? –Through the use of new and delete operators

new When we want to create memory we can do so with new int *myArray; myArray = new int [5]; Operating system will create a space in memory to hold 5 ints and return a pointer to the memory

What’s the difference Without new arrays size must be a constant –Means we need to decide size of arrays at design time not execution time dynamic memory allocation allows assigning memory during the execution of the program using any variable, constant or combination of both as size.

Who manages memory The dynamic memory is generally managed by the operating system –in multitasking interfaces it can be shared between several applications. There is a possibility that the memory can be depleted. –If the operating system cannot allocate the requested memory, it returns a null pointer. –This means you should check for it: int *myArray myArray = new int [5]; if (myArray == NULL) { // error assigning memory. Take measures. };

The delete operator Once memory is no longer needed it should be freed –Make it available for future requests of dynamic memory. –The operator delete exists for this purpose, whose form is:

An Example include #include using namespace std; int main () { char input [100]; int i,n; long *pArray; cout > i; pArray = new long[i]; if (pArray == NULL) exit (1); for (n=0; n > pArray[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << pArray[n] << ", "; delete[] pArray; return 0; }

Memory Leaks Happens when you forget to free a block of memory allocated with the new operator or when you make it impossible to do so As a consequence your application may eventually run out of memory and may even cause the system to crash.

Leak example 1 Deleting memory before reallocating it char *string; string = new char[20]; string = new char[30]; delete [] string; How can we fix it and what exactly is the problem?

Leak example 2 Be sure to have a pointer to each dynamic variable: char *first_string = new char[20]; char *second_string = new char[20]; strcpy(first_string, "leak"); second_string = first_string; strcpy(second_string, first_string); delete [] second_string; What happened is that the address of the dynamic variable associated with second_string (as a side-effect of the pointer assignment) is lost so we cannot delete it from the heap anymore. Thus the last line of code only frees the dynamic variable associated with first_string, which is not what we wanted.

Leak Example 3 Local pointers: void leak() { int k; char *cp = new char('E'); delete cp; } What happens of cp is not deleted? It seems that it would be destroyed when the function returns Actually the pointer is but not it’s memory

Singleton Classes Occasionally you want to create class that doesn’t need multiple instances –Address Book may be one of these Big question is why? –Allows you to get a reference to the single instance that was created Can be from anywhere

The static pointer Singleton class uses a static pointer to access the instance of the object –Remember static variables are declared on the heap Hold there value through the life of the program –Defined as follows: class addressBook { private: static addressBook *pInstance; }

Accessor Method Once you have created the static pointer –You need to create a public accessor method to retrieve the pointer: class addressBook { private: static addressBook *pInstance; public: static addressBook *Instance(); }

And the function Body Notice the declaration before the function –This is needed to create the pointer addressBook * addressBook::pInstance = NULL; addressBook *addressBook::Instance() { if(pInstance == NULL) { pInstance = new addressBook; } return pInstance; }