computer science hw

profile47290v3o0
chapter08_2.pptx

Chapter 8

Strings

Random Numbers

Enumerated Types

The string Type

The string data type

To hold text data, such as a person's name or e-mail address, C++ uses the string type.

The string type is kept in its own library:

#include <string>

A string variable is created just like any other variable:

string variableName;

A string variable may be initialized upon declaration in the usual fashion.

Input and output of strings is just like any other variable type.

Examples

Declaring and initializing a string variable:

string today = "Tuesday"; // initialization

string tomorrow; //an empty string ""

Input and Output:

cout << "I think today is " << today << endl; cout << "What day do you think it is tomorrow? "; cin >> tomorrow; cout << "OK, so tomorrow is " << tomorrow << endl;

Reading text with multiple words

To read in text that contains spaces we use the getline():

getline (InputSource, destinationVariable);

getline() command will read in all information until it encounters an end of line.

Note that using getline() after using >> can cause problems. We can fix these problems using the method cin.ignore().

Example

cout << "Please enter your age: ";

int age;

cin >> age;

cout << "Please enter your full name: ";

cin.ignore();

string fullName;

getline (cin, fullName);

cout << "Thank you, " << fullName << ". ";

cout << "Your are " << age << “ years old.";

Assignment and concatenation

The = sign is used for assignment, just as with other variables.

That is, the value of the expression on the right of the = is assigned to the variable on the left.

The + operator concatenates two strings

That is, it appends one string to the end of another.

Example

string day = "Tuesday"; cout << "Today is " << day << "." << endl; string date = "March 8"; cout << "Today is " << date << "." << endl; date = day + ", " + date; cout << "Today is " << date << "." << endl;

The segment of code about will output:

Today is Tuesday. Today is March 8. Today is Tuesday, March 8.

The index system

A string is a collection of characters.

Each character inside a string has an index indicating its location inside the string.

The first character in the string has index zero. The last character has an index one less than the size of the string.

The subscript operator

In order to access a character inside a string we can use the subscript operator [] and a valid index value.

Example:

string course = "CS 143";

char firstLetter = course[0]; //C

char lastChar = course[5]; // 3

Comparing Strings

The relational operators can be used to compare strings.

Example:

string name1 = "Mary";

string name2 = "Mark";

if ( name1 == name2 )

cout << "The names are the same" ;

else if ( name1 < name2 )

cout << "In alphabetical order: "

<< name1 << " " << name2 ;

else

cout << "In alphabetical order: "

<< name2 << " " << name1 ;

11

How does string comparison work?

In memory characters are stored using numeric codes.

The most commonly used code is ASCII: http ://asciiset.com/

Each letter (a-z, A-Z), digit (0-9), and other characters have a code associated with them:

‘A’ – ‘Z’: codes 65 – 90

‘a’ – ‘z’: codes 97 – 122

‘0’ – ‘9’ : codes 48 – 57

When the relational operators compare two strings:

They compare the strings character-by-character

They actually compare the codes for the characters

12

Example

If one of the strings in a comparison is shorter than the other one, only the corresponding characters are compared.

If the corresponding characters are identical, the shorter string is consider less than the longer string

Mary > Mark because: y > k

or in other words: 121 > 107

121

107

114

97

77

114

97

77

ASCII Codes

String Methods

The string type comes with a collection of very useful methods.

Remember that in order to invoke a method your must use the dot notation.

Some methods return values and some don’t

Some methods have parameters and some don’t

returnValue = stringObject.methodName(arguments);

length() and size()

Both of these methods return the number of characters in the string.

The count will include blank space and special characters if the string contains these.

The type of the returned value is int.

Example

string course = "CS 143"; cout << "The string " << course << " has "     << course.size()

<< " characters (including blanks). " ; cout << "That means " << course.length() - 1

<< " letters.";

The at() method

Another way to access the characters in a string is the at(index) method.

This method takes as its input a valid index value

This method returns the character (char) at the given index value.

Example:

string course = "CS 143";

char firstLetter = course.at(0); //C

char lastChar = course.at(course.size() -1); // 3

The clear() and empty() methods

The clear() method removes all the elements in a string (and resets its size to zero).

The empty() method returns true if the string is empty, false otherwise.

Example:

string course = "CS 143";

course.clear(); //now course is an empty string ""

if ( course.empty() )

cout << "There are 0 characters in the string";

push_back()and append() methods

push_back(newChar): appends the char newChar to the end of the string.

append(secondStr): appends a copy of the string secondString.

Example:

string course = "CS 143";

course.append(" C++"); //course is now: CS 143 C++

course.push_back('!'); //course is now: CS 143 C++!

The replace() method

replace(index, num, subString) replaces num characters starting at index with a copy of the string subString.

Example:

string course = "CS 143";

course.replace(3, 3, "171"); //course is now: CS 171

erase(), insert()and resize() methods

erase(index, n) deletes n characters of the string, starting at index.

insert(index, subStr) inserts the string subStr starting at index.

resize(newSize) resizes the string to have newSize characters.

If decrease, drops extra characters.

If increase, sets new characters to null ('\0', ASCII value 0).

Example:

string course = "CS 143";

course.erase(2, 1); //course is now: CS143

course.insert(2, "---"); //course is now: CS---143

course.resize(2); //course is now: CS

Searching a string

You can use the find() method to search for a substring in a string.

There are two ways you can use the find() method:

find(item)

find(item, startPoint)

Item: the substring we are looking for

startPoint: an index where to start the search

This method returns the index of the first occurrence if item in the string (if found). Otherwise it returns -1

Searching a string

The rfind() method works similar to find() except that it starts the search from the end/back of the string and searches backwards through the string to the beginning/front.

rfind stands for reverse find.

Example: find()

string course = "CS 143";

int location, secondS;

location = course.find("143"); //location = 3

location = course.find("171"); //location = -1

location = course.find("S"); //location = 1

secondS = course.find("S",location + 1); //secondS = -1

Example: rfind()

string course = "CS 143";

int location, secondS;

location = course.rfind("143"); //location = 3

location = course.rfind("171"); //location = -1

location = course.rfind("S"); //location = 1

secondS = course.rfind("S",location - 1);//secondS = -1

Obtaining substrings

The subsrt() method allows you to obtain a substring from a string.

subsrt(index, howMany);

Index: the index of the first character to obtain

howMany: how many characters to obtain

This method returns a string.

Example

string course = "CS 143";

int blankPos;

blankPos = course.find(" "); // blankPos = 2

string subject, number;

subject = course.substr(0, blankPos); //get 2 chars

int qty = course.size() – blankPos - 1; //qty = 3

number = course.substr(blankPos + 1, qty); //get 3 chars

Character operations

The ctype library provides access to several functions for working with characters

To access the functions you must use the directive:

#include <ctype>

Function Description Example
isalpha(character) Returns true if character is a letter (a-z or A-Z) isalpha('A') // true isalpha('7') // false
isdigit(character) Returns true if character is a digit (0-9) isdigit('A') // false isdigit('7’) // true
isspace(character) Returns true if character is a whitespace isspace(' ') // true isspace('\n') // true isspace('x') // false
toupper(character) Returns a uppercase version of the character toupper('a') // A
tolower(character) Returns a lowercase version of the character tolower('A') // a

Random Numbers

Random Numbers

Random number: an unpredictable number

Generated by a formula  pseudo-random numbers but close enough

To generate random numbers we need functions and features from the cstdlib header file

The rand() function:

Returns a random number between 0 and RAND_MAX

RAND_MAX is an integer constant defined in cstdlib

RAND_MAX = 32767

Random Numbers

In order to generate a random number within a given range [upper, lower] we will use this formula:

int n = (upper–lower+1)*(rand()/(RAND_MAX+1.0))+lower;

Example: Generate random numbers between 1 and 6 (to simulate rolling a die for example)

int n = (6 – 1 + 1) * ( rand()/(RAND_MAX+1.0) ) + 1;

int n = ( 6 ) * ( rand()/(RAND_MAX+1.0) ) + 1;

int n = 6 * [0, 0.999] + 1 ;

int n = 6 * 0 + 10  1

int n = 6 * 0.999 + 1  5.994 + 1  6.994  6

Note: for the example we are testing the edge cases

More Examples

[10, 20]

int n = (11) * (rand() / (RAND_MAX + 1.0)) + 10 ;

int n = 11 * [0, 0.999] + 10 ;

int n = 11 * 0 + 10  10

int n = 11 * 0.999 + 10  10.989 + 10  20.98  20

[-10, 15]

int n = (15–(-10)+1)*(rand()/(RAND_MAX+1.0))+(-10);

int n = 26 * [0, 0.999] - 10 ;

int n = 26 * 0 – 10 ;  -10

int n = 26 * (0.999) – 10  25.97 – 10  15.97  15

Reproducible/Irreproducible Sequences

rand() uses an internal formula to produce random numbers

That formula has a value, called the seed, which is used to produce the first random number.

The next random number is generated based on the first random number.

The next random number is generated based on the previous random number.

Consequence: for a given seed, the sequence of random numbers is always the same.

Changing the seed

The srand(int) function allows us to change the value of the seed.

But the value of the seed should be changed each time we run the program.

We will use the help of the time() function from the ctime library:

time(0) returns the number of seconds that have passed since January 1, 1970 0:0:0 GMT and the machine’s current time.

int seed = static cast<int>( time(0) ) ;

srand(seed)

Example

#include <ctime>

#include <cstdlib>

#include <iostream>

using namespace std;

int main ()

{

int seed = static_cast<int>( time( 0 ));

srand( seed );

cout << "Here is a sequence of 5 random numbers: ";

for (int i = 1; i <= 5 ; i++)

cout << rand() << " " ;

return 0;

}

Enumerated Types

Enumerated types

The enum command allows us to create simple new data types

Types created with enum have a limited set of values (or names).

These values are really nothing more than const ints, so it's common practice to write them all in caps.

Once the new type is created, it behaves (more or less) like any other type.

You create variables of that type and assign it values from the list.

Declaring Enumerated Types

The generic format of enum is:

enum TypeName {value1, value2, value3, ... };

Examples:

enum Direction {NORTH, SOUTH, EAST, WEST};

enum Color {RED, BLUE, YELLOW, BLACK, WHITE};

enum Season {FALL, WINTER, SPRING, SUMMER};

Note that each value is an identifier, not a string.

By convention an enumerated type is named with the first letter of each word capitalized and a value of an enumerated type is named like a constant with all uppercase letters.

Declaring variables

Once a type is defined, you can declare a variable of that type:

Season current;

The variable forward can hold one of the values defined in the enumerated type.

current = WINTER;

As with any other type, you can declare and initialize a variable in one statement:

Season current = WINTER;

Enumerated values

Enumerated values are stored as integers in memory.

By default the values correspond to 0, 1, 2….., in order of their appearance in the list.

Example:

enum Season {FALL, WINTER, SPRING, SUMMER};

FALL corresponds to the integer value 0, WINTER to 1, SPRING to 2, and SUMMER to 3.

Enumerated values

You can explicitly assign an enumerated value with any integer value.

Example:

enum Season {FALL = 20, WINTER = 30,

SPRING = 40, SUMMER = 50};

If you assign integer values for some values in the enumerated type declaration, the other values will receive default values.

Example:

enum Season {FALL, WINTER, SPRING = 40, SUMMER};

FALL corresponds to the integer value 0, WINTER to 1, SPRING to 40, and SUMMER to 41.

Manipulating enumerated types

One popular way of manipulating a variable of an enumerated type is with the switch statement.

Example:

switch (current)

{

case FALL:

//process FALL

break;

case WINTER:

//process WINTER

break;

…etc…

}

What the new type can do

Simple Assignment

Season current = WINTER ;

current = SPRING ;

Season next = current ;

Simple Comparison (== and !=)

if (forward == sunrise)   

cout << "You watch an inspiring sunrise." << endl;

What the new type can do, cont.

Used in functions as parameters and return values.

Season next_season (season current)

{

switch (current)

{

case FALL:

return WINTER;

case WINTER:

return SPRING;

case SPRING:

return SUMMER;

case SUMMER:

return FALL;

}

}

What the new type cannot do

Other math operators do not make sense:

Season current = WINTER;

current = current * 10 ;

Comparison based on inequality (<, <=, >. >=) works, but is often meaningless:

Season next = SPRING ;

if (current >= next )

  Produce meaningful output using <<:

cout << "This is the " << current << " season";

//This line produces output such as "This is the 0 season"

Helper functions

One way to work around the issue with output operator is to use a helper function

string season_name (Season s)

{

switch (s)

{

case FALL:

return "Fall";

case WINTER:

return "Winter";

case SPRING:

return "Spring";

case SUMMER:

return "Summer";

}

}

cout << "This is the " << season_name(current) << " season";

CS 143 Final Exam

Date: Tuesday March 15, 2016

Time: 3:30 PM – 5:30 PM

Room: Disque 103

Bring:

your Drexel student ID

If you do not bring your Drexel ID I will not accept your exam.

Pen/pencil/eraser

Study guide available in Learn

Problets available to study for the final

Assignments for this week

Lab 9 is due at the end of the lab session or by Friday 11:59 PM at the latest.

Hard deadline: you and your partner will not be able to submit after the deadline.

Lab must be submitted via Bb Learn. Submissions via email will not be accepted or graded

Submit the source code as a cpp file. No other formats will be graded.

CodeLab assignment # 9:

Due on Tuesday, March 15 by 11:59 PM

Submit your proof of completion via Bb Learn

Hard deadline: your answers will not be recorded after the deadline.

zyBook Chapter 7: Participation and Challenge Activities

Due on Monday March 15 by 11:59 PM

Hard deadline: late submissions will not be graded