object-oriented programming -- using c++

58
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] http://cse.dlit.edu.tw/~andres

Upload: misty

Post on 14-Jan-2016

44 views

Category:

Documents


0 download

DESCRIPTION

Object-Oriented Programming -- Using C++. Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] http://cse.dlit.edu.tw/~andres. Chapter 5 - Pointers and Strings. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Object-Oriented Programming -- Using C++

1

Object-Oriented Programming-- Using C++

Andres, Wen-Yuan Liao

Department of Computer Science and Engineering

De Lin Institute of Technology

[email protected]

http://cse.dlit.edu.tw/~andres

Page 2: Object-Oriented Programming -- Using C++

2

Chapter 5 - Pointers and Strings

Outline5.1 Introduction5.2 Pointer Variable Declarations and Initialization5.3 Pointer Operators5.4 Calling Functions by Reference5.5 Using const with Pointers5.7 Pointer Expressions and Pointer Arithmetic5.8 Relationship Between Pointers and Arrays5.9 Arrays of Pointers5.12 Introduction to Character and String Processing

5.12.1 Fundamentals of Characters and Strings

5.12.2 String Manipulation Functions of the String- Handling Library

Page 3: Object-Oriented Programming -- Using C++

3

5.1 Introduction

• Pointers – Powerful, but difficult to master

– Simulate pass-by-reference

– Close relationship with arrays and strings

Page 4: Object-Oriented Programming -- Using C++

4

5.2 Pointer Variable Declarations and Initialization

• Pointer variables– Contain memory addresses as values – Normally, variable contains specific value (direct reference)– Pointers contain address of variable that has specific value

(indirect reference)

• Indirection– Referencing value through pointer

• Pointer declarations– * indicates variable is pointer

int *myPtr;

declares pointer to an int, pointer of type int * – Multiple pointers require multiple asterisks

int *myPtr1, *myPtr2;

count

7

countPtr

 

count

7

intmyPtr

Page 5: Object-Oriented Programming -- Using C++

5

5.2 Pointer Variable Declarations and Initialization

• Can declare pointers to any data type• Pointer initialization

– Initialized to 0, NULL, or address• 0 or NULL points to nothing

Page 6: Object-Oriented Programming -- Using C++

6

5.3 Pointer Operators

• & (address operator)– Returns memory address of its operand

– Example int y = 5;int *yPtr;yPtr = &y; // yPtr gets address of y

– yPtr “points to” y

yPtr

y5

yPtr

500000 600000

y

600000 5

Page 7: Object-Oriented Programming -- Using C++

7

5.3 Pointer Operators

• * (indirection/dereferencing operator)– Returns synonym for object its pointer operand points to– *yPtr returns y (because yPtr points to y).

– dereferenced pointer is lvalue*yptr = 9; // assigns 9 to y

• * and & are inverses of each other

Page 8: Object-Oriented Programming -- Using C++

Outline

8

fig05_04.cpp(1 of 2)

10 int a; // a is an integer11 int *aPtr; // aPtr is a pointer to an integer13 a = 7;14 aPtr = &a; // aPtr assigned address of a15 16 cout << "The address of a is " << &a17 << "\nThe value of aPtr is " << aPtr;18 19 cout << "\n\nThe value of a is " << a20 << "\nThe value of *aPtr is " << *aPtr;21 22 cout << "\n\nShowing that * and & are inverses of "23 << "each other.\n&*aPtr = " << &*aPtr24 << "\n*&aPtr = " << *&aPtr << endl;

The address of a is 0012FED4

The value of aPtr is 0012FED4

 

The value of a is 7

The value of *aPtr is 7

 

Showing that * and & are inverses of each other.

&*aPtr = 0012FED4

*&aPtr = 0012FED4

aPtr

12FED4

a

12FED4 7

Page 9: Object-Oriented Programming -- Using C++

9

5.4 Calling Functions by Reference

• 3 ways to pass arguments to function– Pass-by-value

– Pass-by-reference with reference arguments

– Pass-by-reference with pointer arguments

• return can return one value from function• Arguments passed to function using reference

arguments– Modify original values of arguments

– More than one value “returned”

Page 10: Object-Oriented Programming -- Using C++

10

5.4 Calling Functions by Reference

• Pass-by-reference with pointer arguments– Simulate pass-by-reference

• Use pointers and indirection operator

– Pass address of argument using & operator

– Arrays not passed with & because array name already pointer– * operator used as alias/nickname for variable inside of

function

Page 11: Object-Oriented Programming -- Using C++

Outline

11

fig05_06.cpp(1 of 2)

1 // Fig. 5.6: fig05_06.cpp2 // Cube a variable using pass-by-value.3 #include <iostream>5 using std::cout;6 using std::endl;8 int cubeByValue( int ); // prototype10 int main()11 {12 int number = 5;14 cout << "The original value of number is " << number;17 number = cubeByValue( number );19 cout << "\nThe new value of number is " << number << endl;21 return 0; 23 }2526 int cubeByValue( int n ) 27 { 28 return n * n * n; // cube local variable n and return result30 }

The original value of number is 5

The new value of number is 125

5

number

undefined

n

5undefined

125

Page 12: Object-Oriented Programming -- Using C++

Outline

12

fig05_07.cpp(1 of 2)

1 // Fig. 5.7: fig05_07.cpp2 // Cube a variable using pass-by-reference 3 // with a pointer argument.4 #include <iostream>6 using std::cout;7 using std::endl;9 void cubeByReference( int * ); // prototype11 int main()12 {13 int number = 5;14 15 cout << "The original value of number is " << number;18 cubeByReference( &number );20 cout << "\nThe new value of number is " << number << endl;22 return 0; 24 }27 void cubeByReference( int *nPtr ) 28 { 29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr 31 }

The original value of number is 5

The new value of number is 125

5

number

undefined

nPtr

125

Page 13: Object-Oriented Programming -- Using C++

13

5.5 Using const with Pointers

• const qualifier– Value of variable should not be modified– const used when function does not need to change a variable

• Principle of least privilege– Award function enough access to accomplish task, but no more

• Four ways to pass pointer to function– Nonconstant pointer to nonconstant data

• Highest amount of access• data can be modified through the dereferenced pointer• pointer can be modified to point to other data

– Nonconstant pointer to constant data– Constant pointer to nonconstant data– Constant pointer to constant data

• Least amount of access

Page 14: Object-Oriented Programming -- Using C++

Outline

14

1 // Fig. 5.10: fig05_10.cpp2 // Nonconstant pointer to nonconstant data9 #include <cctype> // prototypes for islower and toupper11 void convertToUppercase( char * );13 int main()14 {15 char phrase[] = "characters and $32.98";17 cout << "The phrase before conversion is: " << phrase;18 convertToUppercase( phrase );19 cout << "\nThe phrase after conversion is: " 20 << phrase << endl;22 return 0; 24 }27 void convertToUppercase( char *sPtr ) 28 { 29 while ( *sPtr != '\0' ) { // current character is not '\0'31 if ( islower( *sPtr ) ) // if character is lowercase, 32 *sPtr = toupper( *sPtr ); // convert to uppercase 34 ++sPtr; // move sPtr to next character in string

36 }38 }The phrase before conversion is: characters and $32.98

The phrase after conversion is: CHARACTERS AND $32.98

phrase

sPtr

c h a r … \0C H A R

Page 15: Object-Oriented Programming -- Using C++

15

5.5 Using const with Pointers

• Four ways to pass pointer to function– Nonconstant pointer to nonconstant data

– Nonconstant pointer to constant data• pointer can be modified to point to any data item

• data to which it points cannot be modified through that pointer

– Constant pointer to nonconstant data

– Constant pointer to constant data• Least amount of access

Page 16: Object-Oriented Programming -- Using C++

Outline

16

fig05_11.cpp(1 of 2)

1 // Fig. 5.11: fig05_11.cpp 2 // Nonconstant pointer to constant data 4 #include <iostream>6 using std::cout;7 using std::endl;9 void printCharacters( const char * );11 int main()12 {13 char phrase[] = "print characters of a string";14 15 cout << "The string is:\n";16 printCharacters( phrase );17 cout << endl;19 return 0; 21 }25 void printCharacters( const char *sPtr )26 {27 for ( ; *sPtr != '\0'; sPtr++ ) // no initialization28 cout << *sPtr; 30 }

The string is:

print characters of a string

phrase

const char xPtr

p r i n … \0

Page 17: Object-Oriented Programming -- Using C++

Outline

17

fig05_12.cpp(1 of 1)

fig05_12.cppoutput (1 of 1)

1 // Fig. 5.12: fig05_12.cpp2 // Nonconstant pointer to constant data5 void f( const int * ); // prototype7 int main()8 {9 int y;11 f( &y ); // f attempts illegal modification13 return 0; // indicates successful termination15 } // end main16 19 void f( const int *xPtr )20 {21 *xPtr = 100; // error: cannot modify a const object23 } // end function f

d:\cpphtp4_examples\ch05\Fig05_12.cpp(21) : error C2166: l-value specifies const object

y

const int * xPtr

100

Page 18: Object-Oriented Programming -- Using C++

18

5.5 Using const with Pointers

• Four ways to pass pointer to function– Nonconstant pointer to nonconstant data

– Nonconstant pointer to constant data

– Constant pointer to nonconstant data• pointer always points to the same memory location

• data at that location can be modified through the pointer

– Constant pointer to constant data• Least amount of access

Page 19: Object-Oriented Programming -- Using C++

Outline

19

fig05_13.cpp(1 of 1)

fig05_13.cppoutput (1 of 1)

1 // Fig. 5.13: fig05_13.cpp2 // Attempting to modify a constant pointer to3 // non-constant data.5 int main()6 {7 int x, y;12 int * const ptr = &x; 13 14 *ptr = 7; // allowed: *ptr is not const15 ptr = &y; // error: ptr is const; cannot assign new address17 return 0; 19 }

d:\cpphtp4_examples\ch05\Fig05_13.cpp(15) : error C2166: l-value specifies const object

x y int * const ptr7

Page 20: Object-Oriented Programming -- Using C++

20

5.5 Using const with Pointers

• Four ways to pass pointer to function– Nonconstant pointer to nonconstant data

– Nonconstant pointer to constant data

– Constant pointer to nonconstant data

– Constant pointer to constant data• pointer always points to the same memory location

• data at that location cannot be modified using the pointer

• Least amount of access

Page 21: Object-Oriented Programming -- Using C++

Outline

21

fig05_14.cpp(1 of 1)

1 // Fig. 5.14: fig05_14.cpp2 // Attempting to modify a constant pointer to constant data.3 #include <iostream>5 using std::cout;6 using std::endl;8 int main()9 {10 int x = 5, y;15 const int *const ptr = &x; 16 17 cout << *ptr << endl;18 19 *ptr = 7; // error: *ptr is const; cannot assign new value 20 ptr = &y; // error: ptr is const; cannot assign new address22 return 0; 24 }

d:\cpphtp4_examples\ch05\Fig05_14.cpp(19) : error C2166: l-value specifies const object

d:\cpphtp4_examples\ch05\Fig05_14.cpp(20) : error C2166: l-value specifies const object

5const int x y int * const ptr7

Page 22: Object-Oriented Programming -- Using C++

22

5.5 Using const with Pointers

• const pointers– Always point to same memory location

– Default for array name

– Must be initialized when declared

Page 23: Object-Oriented Programming -- Using C++

23

5.7 Pointer Expressions and Pointer Arithmetic

• Pointer arithmetic– Increment/decrement pointer (++ or --)

– Add/subtract an integer to/from a pointer( + or += , - or -=)

– Pointers may be subtracted from each other

– Pointer arithmetic meaningless unless performed on pointer to array

• 5 element int array on a machine using 4 byte ints– vPtr points to first element v[ 0 ], which is at location 3000

vPtr = 3000

– vPtr += 2; sets vPtr to 3008vPtr points to v[ 2 ]

pointer variable vPtr

v[0] v[1] v[2] v[4]v[3]

3000 3004 3008 3012 3016

location

 

Page 24: Object-Oriented Programming -- Using C++

24

5.7 Pointer Expressions and Pointer Arithmetic

• Subtracting pointers– Returns number of elements between two addresses

vPtr2 = v[ 2 ];vPtr = v[ 0 ];vPtr2 - vPtr == 2

• Pointer assignment– Pointer can be assigned to another pointer if both of same

type

– If not same type, cast operator must be used

Page 25: Object-Oriented Programming -- Using C++

25

5.8 Relationship Between Pointers and Arrays

• Arrays and pointers closely related– Array name like constant pointer

– Pointers can do array subscripting operations

• Accessing array elements with pointers– Element b[ n ] can be accessed by *( bPtr + n )

• Called pointer/offset notation

– Addresses• &b[ 3 ] same as bPtr + 3

– Array name can be treated as pointer• b[ 3 ] same as *( b + 3 )

– Pointers can be subscripted (pointer/subscript notation)• bPtr[ 3 ] same as b[ 3 ]

Page 26: Object-Oriented Programming -- Using C++

Outline

26

fig05_20.cpp(1 of 2)

1 // Fig. 5.20: fig05_20.cpp11 int b[] = { 10, 20, 30, 40 };12 int *bPtr = b; // set bPtr to point to array b……18 for ( int i = 0; i < 4; i++ )19 cout << "b[" << i << "] = " << b[ i ] << '\n';……26 for ( int offset1 = 0; offset1 < 4; offset1++ )27 cout << "*(b + " << offset1 << ") = " 28 << *( b + offset1 ) << '\n';……33 for ( int j = 0; j < 4; j++ )34 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n';……39 for ( int offset2 = 0; offset2 < 4; offset2++ )40 cout << "*(bPtr + " << offset2 << ") = "41 << *( bPtr + offset2 ) << '\n';43 return 0; 45 }

Page 27: Object-Oriented Programming -- Using C++

Outline

27

fig05_20.cppoutput (1 of 1)

Array b printed with:

 

Array subscript notation

b[0] = 10

b[1] = 20

b[2] = 30

b[3] = 40

 

Pointer/offset notation where the pointer is the array name

*(b + 0) = 10

*(b + 1) = 20

*(b + 2) = 30

*(b + 3) = 40

Pointer subscript notation

bPtr[0] = 10

bPtr[1] = 20

bPtr[2] = 30

bPtr[3] = 40

 

Pointer/offset notation

*(bPtr + 0) = 10

*(bPtr + 1) = 20

*(bPtr + 2) = 30

*(bPtr + 3) = 40

Page 28: Object-Oriented Programming -- Using C++

Outline

28

fig05_21.cpp(1 of 2)

1 // Fig. 5.21: fig05_21.cpp……9 void copy1( char *, const char * ); // prototype10 void copy2( char *, const char * ); // prototype12 int main()13 {14 char string1[ 10 ];15 char *string2 = "Hello";16 char string3[ 10 ];17 char string4[] = "Good Bye";18 19 copy1( string1, string2 );20 cout << "string1 = " << string1 << endl;21 22 copy2( string3, string4 );23 cout << "string3 = " << string3 << endl;25 return 0; 27 }

Page 29: Object-Oriented Programming -- Using C++

Outline

29

fig05_21.cpp(2 of 2)

fig05_21.cppoutput (1 of 1)

30 void copy1( char *s1, const char *s2 )31 {32 for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ )33 ; // do nothing in body 34 35 }36 38 void copy2( char *s1, const char *s2 )39 {40 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ )41 ; // do nothing in body 43 }

string1 = Hello

string3 = Good Bye

Page 30: Object-Oriented Programming -- Using C++

30

5.9 Arrays of Pointers

• Arrays can contain pointers– Commonly used to store array of strings

char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" };

– Each element of suit points to char * (a string)

– Array does not store strings, only pointers to strings

– suit array has fixed size, but strings can be of any size

suit[3]

suit[2]

suit[1]

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

 

Page 31: Object-Oriented Programming -- Using C++

31

Exercises #2

• 3.11• 3.16 (b), (e), (f)• 3.53• 4.6• 4.7• 4.18• 5.9 (a), (b), (h), (i), (j)• 5.22

Page 32: Object-Oriented Programming -- Using C++

32

5.12.1 Fundamentals of Characters and Strings

• Character constant– Integer value represented as character in single quotes– 'z' is integer value of z

• 122 in ASCII

• String– Series of characters treated as single unit– Can include letters, digits, special characters +, -, * ...– String literal (string constants)

• Enclosed in double quotes, for example:"I like C++"

– Array of characters, ends with null character '\0'– String is constant pointer

• Pointer to string’s first character– Like arrays

Page 33: Object-Oriented Programming -- Using C++

33

5.12.1 Fundamentals of Characters and Strings

• String assignment– Character array

• char color[] = "blue";

– Creates 5 element char array color

• last element is '\0'

– Variable of type char *• char *colorPtr = "blue";

– Creates pointer colorPtr to letter b in string “blue”• “blue” somewhere in memory

– Alternative for character array• char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };

Page 34: Object-Oriented Programming -- Using C++

34

5.12.1 Fundamentals of Characters and Strings

• Reading strings– Assign input to character array word[ 20 ]

cin >> word

• Reads characters until whitespace or EOF

• String could exceed array size

cin >> setw( 20 ) >> word;• Reads 19 characters (space reserved for '\0')

Page 35: Object-Oriented Programming -- Using C++

35

5.12.1 Fundamentals of Characters and Strings

• cin.getline– Read line of text– cin.getline( array, size, delimiter );– Copies input into specified array until either

• One less than size is reached• delimiter character is input

– Examplechar sentence[ 80 ];

cin.getline( sentence, 80, '\n' );

Page 36: Object-Oriented Programming -- Using C++

36

5.12.2 String Manipulation Functions of the String-handling Library

• String handling library <cstring> provides functions to– Manipulate string data

– Compare strings

– Search strings for characters and other strings

– Tokenize strings (separate strings into logical pieces)

Page 37: Object-Oriented Programming -- Using C++

37

5.12.2 String Manipulation Functions of the String-handling Library

char *strcpy( char *s1, const char *s2 );

Copies the string s2 into the character

array s1. The value of s1 is returned. First argument must be large enough to store string and terminating null character.

char *strncpy( char *s1, const char *s2, size_t n );

Copies at most n characters of the string s2 into the character array s1. The value of s1 is returned. Does not necessarily copy terminating null character.

char *strcat( char *s1, const char *s2 );

Appends the string s2 to the string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. Ensure first argument large enough to store concatenated result and null character.

char *strncat( char *s1, const char *s2, size_t n );

Appends at most n characters of string s2 to string s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned. Appends terminating null character to result.

Page 38: Object-Oriented Programming -- Using C++

Outline

38

fig05_28.cpp(1 of 2)

12 char x[] = "Happy Birthday to You";13 char y[ 25 ];14 char z[ 15 ];16 strcpy( y, x ); // copy contents of x into y22 strncpy( z, x, 14 ); // does not copy null character23 z[ 14 ] = '\0'; // append '\0' to z's contents

The string in array x is: Happy Birthday to You

The string in array y is: Happy Birthday to You

The string in array z is: Happy Birthday

Page 39: Object-Oriented Programming -- Using C++

Outline

39

fig05_29.cpp(1 of 2)

12 char s1[ 20 ] = "Happy ";13 char s2[] = "New Year ";14 char s3[ 40 ] = "";18 strcat( s1, s2 ); // concatenate s2 to s124 strncat( s3, s1, 6 ); // places '\0' after last character29 strcat( s3, s1 ); // concatenate s1 to s3

s1 = Happy

s2 = New Year

 

After strcat(s1, s2):

s1 = Happy New Year

s2 = New Year

 

After strncat(s3, s1, 6):

s1 = Happy New Year

s3 = Happy

 

After strcat(s3, s1):

s1 = Happy New Year

s3 = Happy Happy New Year

Page 40: Object-Oriented Programming -- Using C++

40

5.12.2 String Manipulation Functions of the String-handling Library

int strcmp( const char *s1, const char *s2 );

Compares the string s1 with the string s2. The function returns a value of zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively. Compares character by character. Strings compared using numeric codes.

Character codes / character sets:

ASCII (American Standard Code for Information Interchange)

EBCDIC (Extended Binary Coded Decimal Interchange Code).

int strncmp( const char *s1, const char *s2, size_t n );

Compares up to n characters of the string s1 with the string s2. The function returns zero, less than zero or greater than zero if s1 is equal to, less than or greater than s2, respectively. Stops comparing if reaches null character in one of arguments

size_t strlen( const char *s );

Determines the length of string s. The number of characters preceding the terminating null character is returned.

Page 41: Object-Oriented Programming -- Using C++

Outline

41

fig05_30.cpp(1 of 2)

16 char *s1 = "Happy New Year";17 char *s2 = "Happy New Year";18 char *s3 = "Happy Holidays";22 strcmp( s1, s2 ); 24 strcmp( s1, s3 );25 strcmp( s3, s1 );28 strncmp( s1, s3, 6 );29 strncmp( s1, s3, 7 ); 31 strncmp( s3, s1, 7 );

s1 = Happy New Year

s2 = Happy New Year

s3 = Happy Holidays

strcmp(s1, s2) = 0

strcmp(s1, s3) = 1

strcmp(s3, s1) = -1

strncmp(s1, s3, 6) = 0

strncmp(s1, s3, 7) = 1

strncmp(s3, s1, 7) = -1

Page 42: Object-Oriented Programming -- Using C++

Outline

42

fig05_32.cpp(1 of 1)

12 char *string1 = "abcdefghijklmnopqrstuvwxyz";13 char *string2 = "four";14 char *string3 = "Boston";17 strlen( string1 );19 strlen( string2 );21 strlen( string3 );

The length of "abcdefghijklmnopqrstuvwxyz" is 26

The length of "four" is 4

The length of "Boston" is 6

Page 43: Object-Oriented Programming -- Using C++

43

18.9 Character-Handling Library

• Character Handling Library– <cctype>– Functions to perform tests and manipulations on characters

– Pass character as argument• Character represented by an int

– char does not allow negative values

• Characters often manipulated as ints• EOF usually has value -1

Page 44: Object-Oriented Programming -- Using C++

44

18.9 Character-Handling Library

isalpha( int c ) Returns true if c is a letter (A-Z, a-z). Returns false otherwise.

isdigit ( int c ) Returns true if digit (0-9).

isalnum ( int c ) Returns true if letter or digit (A-Z, a-z, 0-9).

isxdigit ( int c ) Returns true if hexadecimal digit (A-F, a-f, 0-9).

islower ( int c ) Returns true if lowercase letter (a-z)

isupper ( int c ) Returns true if uppercase letter (A-Z)

int tolower ( int c )

If passed uppercase letter, returns lowercase letter (A to a). Otherwise, returns original argument

int toupper ( int c )

As above, but turns lowercase letter to uppercase (a to A).

Page 45: Object-Oriented Programming -- Using C++

45

18.9 Character-Handling Library

isspace ( int c ) Returns true if space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v'

iscntrl ( int c ) Returns true if control character, such as tabs, form feed, alert ('\a'), backspace('\b'), carriage return, newline

ispunct ( int c ) Returns true if printing character other than space, digit, or letter $ # ( ) [ ] { } ; : %, etc

isprint ( int c ) Returns true if character can be displayed (including space)

isgraph ( int c ) Returns true if character can be displayed, not including space

Page 46: Object-Oriented Programming -- Using C++

Outline

46

fig18_17.cpp(1 of 2)

1 // Fig. 18.17: fig18_17.cpp13 << ( isdigit( '8' ) ? "8 is a" : "8 is not a" ) 15 << ( isdigit( '#' ) ? "# is a" : "# is not a" ) 19 << ( isalpha( 'A' ) ? "A is a" : "A is not a" ) 21 << ( isalpha( 'b' ) ? "b is a" : "b is not a" ) 23 << ( isalpha( '&' ) ? "& is a" : "& is not a" ) 25 << ( isalpha( '4' ) ? "4 is a" : "4 is not a" )29 << ( isalnum( 'A' ) ? "A is a" : "A is not a" )31 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" )33 << ( isalnum( '#' ) ? "# is a" : "# is not a" )37 << ( isxdigit( 'F' ) ? "F is a" : "F is not a" )39 << ( isxdigit( 'J' ) ? "J is a" : "J is not a" )41 << ( isxdigit( '7' ) ? "7 is a" : "7 is not a" )43 << ( isxdigit( '$' ) ? "$ is a" : "$ is not a" )45 << ( isxdigit( 'f' ) ? "f is a" : "f is not a" )

Page 47: Object-Oriented Programming -- Using C++

Outline

47

fig18_17.cppoutput (1 of 1)

According to isdigit:

8 is a digit

# is not a digit

According to isalpha:

A is a letter

b is a letter

& is not a letter

4 is not a letter

According to isalnum:

A is a digit or a letter

8 is a digit or a letter

# is not a digit or a letter

According to isxdigit:

F is a hexadecimal digit

J is not a hexadecimal digit

7 is a hexadecimal digit

$ is not a hexadecimal digit

f is a hexadecimal digit

Page 48: Object-Oriented Programming -- Using C++

Outline

48

fig18_18.cpp(1 of 2)

13 << ( islower( 'p' ) ? "p is a" : "p is not a" ) 15 << ( islower( 'P' ) ? "P is a" : "P is not a" ) 17 << ( islower( '5' ) ? "5 is a" : "5 is not a" ) 19 << ( islower( '!' ) ? "! is a" : "! is not a" ) 23 << ( isupper( 'D' ) ? "D is an" : "D is not an" ) 25 << ( isupper( 'd' ) ? "d is an" : "d is not an" ) 27 << ( isupper( '8' ) ? "8 is an" : "8 is not an" ) 29 << ( isupper( '$' ) ? "$ is an" : "$ is not an" ) 33 << static_cast< char >( toupper( 'u' ) )35 << static_cast< char >( toupper( '7' ) )37 << static_cast< char >( toupper( '$' ) )39 << static_cast< char >( tolower( 'L' ) ) << endl;

Page 49: Object-Oriented Programming -- Using C++

Outline

49

fig18_18.cpp(2 of 2)

According to islower:

p is a lowercase letter

P is not a lowercase letter

5 is not a lowercase letter

! is not a lowercase letter

According to isupper:

D is an uppercase letter

d is not an uppercase letter

8 is not an uppercase letter

$ is not an uppercase letter

u converted to uppercase is U

7 converted to uppercase is 7

$ converted to uppercase is $

L converted to lowercase is l

Page 50: Object-Oriented Programming -- Using C++

Outline

50

fig18_19.cpp(1 of 2)

13 << ( isspace( '\n' ) ? "is a" : "is not a" )15 << ( isspace( '\t' ) ? "is a" : "is not a" )17 << ( isspace( '%' ) ? "% is a" : "% is not a" )21 << ( iscntrl( '\n' ) ? "is a" : "is not a" )23 << ( iscntrl( '$' ) ? "$ is a" : "$ is not a" )27 << ( ispunct( ';' ) ? "; is a" : "; is not a" )29 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )31 << ( ispunct( '#' ) ? "# is a" : "# is not a" )35 << ( isprint( '$' ) ? "$ is a" : "$ is not a" )37 << ( isprint( '\a' ) ? "is a" : "is not a" )41 << ( isgraph( 'Q' ) ? "Q is a" : "Q is not a" )43 << ( isgraph( ' ' ) ? "is a" : "is not a" )

Page 51: Object-Oriented Programming -- Using C++

Outline

51

fig18_19.cppoutput (1 of 1)

According to isspace:

Newline is a whitespace character

Horizontal tab is a whitespace character

% is not a whitespace character

According to iscntrl:

Newline is a control character

$ is not a control character

According to ispunct:

; is a punctuation character

Y is not a punctuation character

# is a punctuation character

According to isprint:

$ is a printing character

Alert is not a printing character

According to isgraph:

Q is a printing character other than a space

Space is not a printing character other than a space

Page 52: Object-Oriented Programming -- Using C++

52

18.10 String-Conversion Functions

• String conversion functions– Convert to numeric values, searching, comparison– <cstdlib>– Most functions take const char *

• Do not modify string

Page 53: Object-Oriented Programming -- Using C++

53

18.10 String-Conversion Functions

double atof( const char *nPtr ) Converts string to floating point number (double). Returns 0 if cannot be converted

int atoi( const char *nPtr ) Converts string to integer. Returns 0 if cannot be converted

long atol( const char *nPtr ) Converts string to long integer. If int and long both 4-bytes, then atoi and atol identical

double strtod( const char *nPtr, char **endPtr )

Converts first argument to double, returns that value. Sets second argument to location of first character after converted portion of string

strtod("123.4this is a test", &stringPtr);

Returns 123.4. stringPtr points to "this is a test"

long strtol( const char *nPtr, char **endPtr, int base )

Converts first argument to long, returns that value. Sets second argument to location of first character after converted portion of string. If NULL, remainder of string ignored. Third argument is base of value being converted. Any number 2 – 36. 0 specifies octal, decimal, or hexadecimal.

long strtoul ( const char *nPtr, char **endPtr, int base )

As above, with unsigned long

Page 54: Object-Oriented Programming -- Using C++

Outline

54

fig18_21.cpp(1 of 1)

fig18_21.cppoutput (1 of 1)

1 // Fig. 18.21: fig18_21.cpp12 double d = atof( "99.0" );14 cout << "The string \"99.0\" converted to double is "15 << d << "\nThe converted value divided by 2 is "16 << d / 2.0 << endl;

The string "99.0" converted to double is 99

The converted value divided by 2 is 49.5

1 // Fig. 18.22: fig18_22.cpp12 int i = atoi( "2593" );13 14 cout << "The string \"2593\" converted to int is " << i15 << "\nThe converted value minus 593 is " << i - 593 16 << endl;

The string "2593" converted to int is 2593

The converted value minus 593 is 2000

Page 55: Object-Oriented Programming -- Using C++

Outline

55

fig18_23.cpp(1 of 1)

fig18_23.cppoutput (1 of 1)

1 // Fig. 18.23: fig18_23.cpp12 long x = atol( "1000000" );13 14 cout << "The string \"1000000\" converted to long is " << x15 << "\nThe converted value divided by 2 is " << x / 2 16 << endl;

The string "1000000" converted to long int is 1000000

The converted value divided by 2 is 500000

Page 56: Object-Oriented Programming -- Using C++

Outline

56

fig18_24.cpp(1 of 1)

fig18_24.cppoutput (1 of 1)

1 // Fig. 18.24: fig18_24.cpp12 double d;13 const char *string1 = "51.2% are admitted";14 char *stringPtr;16 d = strtod( string1, &stringPtr );18 cout << "The string \"" << string1 19 << "\" is converted to the\ndouble value " << d 20 << " and the string \"" << stringPtr << "\"" << endl;

The string "51.2% are admitted" is converted to the

double value 51.2 and the string "% are admitted"

Page 57: Object-Oriented Programming -- Using C++

Outline

57

fig18_25.cpp(1 of 1)

12 long x;13 const char *string1 = "-1234567abc";14 char *remainderPtr;16 x = strtol( string1, &remainderPtr, 0 );18 cout << "The original string is \"" << string119 << "\"\nThe converted value is " << x20 << "\nThe remainder of the original string is \""21 << remainderPtr22 << "\"\nThe converted value plus 567 is " 23 << x + 567 << endl;

The original string is "-1234567abc"

The converted value is -1234567

The remainder of the original string is "abc"

The converted value plus 567 is -1234000

Page 58: Object-Oriented Programming -- Using C++

Outline

58

fig18_26.cpp(1 of 1)

12 unsigned long x;13 const char *string1 = "1234567abc";14 char *remainderPtr;16 x = strtoul( string1, &remainderPtr, 0 );18 cout << "The original string is \"" << string119 << "\"\nThe converted value is " << x20 << "\nThe remainder of the original string is \""21 << remainderPtr22 << "\"\nThe converted value minus 567 is " 23 << x - 567 << endl;

The original string is "1234567abc"

The converted value is 1234567

The remainder of the original string is "abc"

The converted value minus 567 is 1234000