chapter 18 - bits, characters, strings and structures

87
2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 18 - Bits, Characters, Strings and Structures Outline 18.1 Introduction 18.2 Structure Definitions 18.3 Initializing Structures 18.4 Using Structures with Functions 18.5 typedef 18.6 Example: High-Performance Card-Shuffling and Dealing Simulation 18.7 Bitwise Operators 18.8 Bit Fields 18.9 Character-Handling Library 18.10 String-Conversion Functions 18.11 Search Functions of the String-Handling Library 18.12 Memory Functions of the String-Handling Library

Upload: deacon

Post on 19-Jan-2016

37 views

Category:

Documents


0 download

DESCRIPTION

Chapter 18 - Bits, Characters, Strings and Structures. Outline 18.1 Introduction 18.2 Structure Definitions 18.3 Initializing Structures 18.4 Using Structures with Functions 18.5 typedef 18.6 Example: High-Performance Card-Shuffling and Dealing Simulation - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

1

Chapter 18 - Bits, Characters, Strings and Structures

Outline18.1 Introduction18.2 Structure Definitions18.3 Initializing Structures18.4 Using Structures with Functions18.5 typedef18.6 Example: High-Performance Card-Shuffling and Dealing Simulation18.7 Bitwise Operators18.8 Bit Fields18.9 Character-Handling Library18.10 String-Conversion Functions18.11 Search Functions of the String-Handling Library18.12 Memory Functions of the String-Handling Library

Page 2: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

2

18.1 Introduction

• Structures, bits, characters, C-style strings– C-like techniques

– Useful for C++ programmers working with legacy C code

• Structures– Hold variables of different data types

– Similar to classes, but all data members public– Examine how to use structures

• Make card shuffling simulation

Page 3: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

3

18.2 Structure Definitions

• Structure definitionstruct Card {

char *face;

char *suit; };

– Keyword struct– Card is structure name

• Used to declare variable of structure type

– Data/functions declared within braces• Structure members need unique names

• Structure cannot contain instance of itself, only a pointer

– Definition does not reserve memory

– Definition ends with semicolon

Page 4: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

4

18.2 Structure Definitions

• Declaration– Declared like other variables: use structure type

• Card oneCard, deck[ 52 ], *cPtr;

– Can declare variables when define structurestruct Card { char *face; char *suit;} oneCard, deck[ 52 ], *cPtr;

Page 5: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

5

18.2 Structure Definitions

• Structure operations– Assignment to a structure of same type

– Taking address (&)

– Accessing members (oneCard.face)

– Using sizeof• Structure may not be in consecutive bytes of memory

• Byte-alignment (2 or 4 bytes) may cause "holes"

Page 6: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

6

18.2 Structure Definitions

• Suppose 2-byte boundary for structure members– Use structure with a char and an int

• char in first byte• int on a 2-byte boundary

• Value in 1-byte hole undefined

– Since hole undefined, structures may not compare equally• Cannot use ==

01100001

20 1 3Byte

00000000 01100001

Page 7: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

7

18.3 Initializing Structures

• Initializer lists (like arrays)– Card oneCard = { "Three", "Hearts" };– Comma-separated values, enclosed in braces

• If member unspecified, default of 0

• Initialize with assignment– Assign one structure to another

Card threeHearts = oneCard;

– Assign members individuallyCard threeHearts;

threeHearts.face = “Three”;

threeHearts.suit = “Hearts”;

Page 8: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

8

18.4 Using Structures with Functions

• Two ways to pass structures to functions– Pass entire structure

– Pass individual members

– Both pass call-by-value

• To pass structures call-by-reference – Pass address

– Pass reference to structure

• To pass arrays call-by-value– Create structure with array as member

– Pass the structure

– Pass-by-reference more efficient

Page 9: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

9

18.5 typedef

• Keyword typedef – Makes synonyms (aliases) for previously defined data types

• Does not create new type, only an alias

– Creates shorter type names

• Example– typedef Card *CardPtr;– Defines new type name CardPtr as synonym for type Card *• CardPtr myCardPtr;• Card * myCardPtr;

Page 10: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

1018.6 Example: High-Performance Card-Shuffling and Dealing

Simulation• Pseudocode

– Create Card structure

– Put cards into array deck• Card deck[ 52 ];

– Shuffle the deck• Swap random cards

– Deal the cards• Go through deck, print face and suit

Page 11: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline11

fig18_02.cpp(1 of 4)

1 // Fig. 18.2: fig18_02.cpp2 // Card shuffling and dealing program using structures.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 using std::left;9 using std::right;10 11 #include <iomanip>12 13 using std::setw;14 15 #include <cstdlib>16 #include <ctime>17 18 // Card structure definition19 struct Card { 20 char *face; 21 char *suit; 22 23 }; // end structure Card 24 25 void fillDeck( Card * const, char *[], char *[] );26 void shuffle( Card * const );27 void deal( Card * const );

Declare the Card structure. In functions, it is used like any other type.

Page 12: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline12

fig18_02.cpp(2 of 4)

28 29 int main()30 {31 Card deck[ 52 ];32 char *face[] = { "Ace", "Deuce", "Three", "Four", 33 "Five", "Six", "Seven", "Eight", "Nine", "Ten", 34 "Jack", "Queen", "King" };35 char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades" };36 37 srand( time( 0 ) ); // randomize 38 39 fillDeck( deck, face, suit );40 shuffle( deck );41 deal( deck );42 43 return 0;44 45 } // end main46

Page 13: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline13

fig18_02.cpp(3 of 4)

47 // place strings into Card structures48 void fillDeck( Card * const wDeck, 49 char *wFace[], char *wSuit[] )50 {51 for ( int i = 0; i < 52; i++ ) {52 wDeck[ i ].face = wFace[ i % 13 ];53 wDeck[ i ].suit = wSuit[ i / 13 ];54 55 } // end for56 57 } // end function fillDeck58 59 // shuffle cards60 void shuffle( Card * const wDeck )61 {62 for ( int i = 0; i < 52; i++ ) {63 int j = rand() % 52;64 Card temp = wDeck[ i ]; 65 wDeck[ i ] = wDeck[ j ];66 wDeck[ j ] = temp; 67 68 } // end for69 70 } // end function shuffle71

Create every face and suit. Note format for accessing a data member in an array of structs.

Pick a random card in deck (0-51) and swap with current card. Notice the use of structure assignment.

Page 14: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline14

fig18_02.cpp(4 of 4)

72 // deal cards73 void deal( Card * const wDeck )74 {75 for ( int i = 0; i < 52; i++ )76 cout << right << setw( 5 ) << wDeck[ i ].face << " of " 77 << left << setw( 8 ) << wDeck[ i ].suit 78 << ( ( i + 1 ) % 2 ? '\t' : '\n' );79 80 } // end function deal

Page 15: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline15

fig18_02.cppoutput (1 of 1)

King of Clubs Ten of Diamonds

Five of Diamonds Jack of Clubs

Seven of Spades Five of Clubs

Three of Spades King of Hearts

Ten of Clubs Eight of Spades

Eight of Hearts Six of Hearts

Nine of Diamonds Nine of Clubs

Three of Diamonds Queen of Hearts

Six of Clubs Seven of Hearts

Seven of Diamonds Jack of Diamonds

Jack of Spades King of Diamonds

Deuce of Diamonds Four of Clubs

Three of Clubs Five of Hearts

Eight of Clubs Ace of Hearts

Deuce of Spades Ace of Clubs

Ten of Spades Eight of Diamonds

Ten of Hearts Six of Spades

Queen of Diamonds Nine of Hearts

Seven of Clubs Queen of Clubs

Deuce of Clubs Queen of Spades

Three of Hearts Five of Spades

Deuce of Hearts Jack of Hearts

Four of Hearts Ace of Diamonds

Nine of Spades Four of Diamonds

Ace of Spades Six of Diamonds

Four of Spades King of Spades

Page 16: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

16

18.7 Bitwise Operators

• Data represented internally as sequences of bits– Each bit can be 0 or 1– 8 bits form a byte

• char is one byte

• Other data types larger (int, long, etc.)

– Low-level software requires bit and byte manipulation• Operating systems, networking

Page 17: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

17

18.7 Bitwise Operators

• Bit operators– Many are overloaded– & (bitwise AND)

• 1 if both bits 1, 0 otherwise

– | (bitwise inclusive OR)• 1 if either bit 1, 0 otherwise

– ^ (bitwise exclusive OR)• 1 if exactly one bit is 1, 0 otherwise

• Alternatively: 1 if the bits are different

– ~ (bitwise one's complement)• Flips 0 bits to 1, and vice versa

Page 18: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

18

18.7 Bitwise Operators

• Bit operators– << (left shift)

• Moves all bits left by specified amount

• Fills from right with 0• 1 << SHIFTAMOUNT

– >> (right shift with sign extension)• Moves bits right by specified amount

• Fill from left can vary

Page 19: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

19

18.7 Bitwise Operators

• Next program– Print values in their binary representation

– Example: unsigned integer 3• 00000000 00000000 00000000 00000011• (For a machine with 4-byte integers)

• Computer stores number in this form

• Using masks– Integer value with specific bits set to 1

– Used to hide some bits while selecting others• Use with AND

Page 20: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

20

18.7 Bitwise Operators

• Mask example– Suppose we want to see leftmost bit of a number

– AND with mask • 10000000 00000000 00000000 00000000 (mask)• 10010101 10110000 10101100 00011000 (number)

– If leftmost bit of number 1• Bitwise AND will be nonzero (true)

– Leftmost bit of result will be 1• All other bits are "masked off" (ANDed with 0)

– If leftmost bit of number 0• Bitwise AND will be 0 (false)

Page 21: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

21

18.7 Bitwise Operators

• To print every bit– Print leftmost digit

– Shift number left

– Repeat

• To create mask– Want mask of 1000000 … 0000– How many bits in unsigned?

• sizeof(unsigned) * 8

– Start with mask of 1• Shift one less time (mask is already on first bit)• 1 << sizeof(unsigned) * 8 - 1• 10000000 00000000 00000000 00000000

Page 22: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline22

fig18_05.cpp(1 of 2)

1 // Fig. 18.5: fig18_05.cpp2 // Printing an unsigned integer in bits.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 #include <iomanip>10 11 using std::setw;12 13 void displayBits( unsigned ); // prototype14 15 int main()16 {17 unsigned inputValue;18 19 cout << "Enter an unsigned integer: ";20 cin >> inputValue;21 displayBits( inputValue );22 23 return 0;24 25 } // end main26

Page 23: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline23

fig18_05.cpp(2 of 2)

fig18_05.cppoutput (1 of 1)

27 // display bits of an unsigned integer value28 void displayBits( unsigned value )29 {30 const int SHIFT = 8 * sizeof( unsigned ) - 1;31 const unsigned MASK = 1 << SHIFT; 32 33 cout << setw( 10 ) << value << " = ";34 35 for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {36 cout << ( value & MASK ? '1' : '0' ); 37 value <<= 1; // shift value left by 138 39 if ( i % 8 == 0 ) // output a space after 8 bits40 cout << ' ';41 42 } // end for43 44 cout << endl;45 46 } // end function displayBits

Enter an unsigned integer: 65000

65000 = 00000000 00000000 11111101 11101000

SHIFT = 32 - 1 = 31MASK = 10000000 00000000 00000000 00000000

Bitwise AND value and mask. If it is nonzero (true), then the leftmost digit is a 1.Shift value left by 1 to

examine next bit. Note use of <<= (same as value = value << 1).

Page 24: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

24

18.7 Bitwise Operators

• Upcoming examples– Demo operators– & (AND)

• x & y

– | (OR)• x | y

– ^ (Exclusive OR)• x ^ y

– ~ (Complement)• ~x

– << and >> (Left shift and right shift)

Page 25: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline25

fig18_07.cpp(1 of 4)

1 // Fig. 18.7: fig18_07.cpp2 // Using the bitwise AND, bitwise inclusive OR, bitwise3 // exclusive OR and bitwise complement operators.4 #include <iostream>5 6 using std::cout;7 using std::cin;8 9 #include <iomanip>10 11 using std::endl;12 using std::setw;13 14 void displayBits( unsigned ); // prototype15 16 int main()17 {18 unsigned number1;19 unsigned number2;20 unsigned mask;21 unsigned setBits;22

Page 26: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline26

fig18_07.cpp(2 of 4)

23 // demonstrate bitwise &24 number1 = 2179876355;25 mask = 1;26 cout << "The result of combining the following\n";27 displayBits( number1 );28 displayBits( mask );29 cout << "using the bitwise AND operator & is\n";30 displayBits( number1 & mask );31 32 // demonstrate bitwise |33 number1 = 15;34 setBits = 241;35 cout << "\nThe result of combining the following\n";36 displayBits( number1 );37 displayBits( setBits );38 cout << "using the bitwise inclusive OR operator | is\n";39 displayBits( number1 | setBits );40 41 // demonstrate bitwise exclusive OR42 number1 = 139;43 number2 = 199;44 cout << "\nThe result of combining the following\n";45 displayBits( number1 );46 displayBits( number2 );47 cout << "using the bitwise exclusive OR operator ^ is\n";48 displayBits( number1 ^ number2 );

Page 27: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline27

fig18_07.cpp(3 of 4)

49 50 // demonstrate bitwise complement51 number1 = 21845;52 cout << "\nThe one's complement of\n";53 displayBits( number1 );54 cout << "is" << endl;55 displayBits( ~number1 );56 57 return 0;58 59 } // end main60 61 // display bits of an unsigned integer value62 void displayBits( unsigned value )63 {64 const int SHIFT = 8 * sizeof( unsigned ) - 1;65 const unsigned MASK = 1 << SHIFT;66 67 cout << setw( 10 ) << value << " = ";68 69 for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {70 cout << ( value & MASK ? '1' : '0' );71 value <<= 1; // shift value left by 172 73 if ( i % 8 == 0 ) // output a space after 8 bits74 cout << ' ';75 76 } // end for

Page 28: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline28

fig18_07.cpp(4 of 4)

fig18_07.cppoutput (1 of 1)

77 78 cout << endl;79 80 } // end function displayBits

The result of combining the following

2179876355 = 10000001 11101110 01000110 00000011

1 = 00000000 00000000 00000000 00000001

using the bitwise AND operator & is

1 = 00000000 00000000 00000000 00000001

 

The result of combining the following

15 = 00000000 00000000 00000000 00001111

241 = 00000000 00000000 00000000 11110001

using the bitwise inclusive OR operator | is

255 = 00000000 00000000 00000000 11111111

 

The result of combining the following

139 = 00000000 00000000 00000000 10001011

199 = 00000000 00000000 00000000 11000111

using the bitwise exclusive OR operator ^ is

76 = 00000000 00000000 00000000 01001100

 

The one's complement of

21845 = 00000000 00000000 01010101 01010101

is

4294945450 = 11111111 11111111 10101010 10101010

Page 29: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline29

fig18_07.cpp(1 of 3)

1 // Fig. 18.11: fig18_11.cpp2 // Using the bitwise shift operators.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 #include <iomanip>10 11 using std::setw;12 13 void displayBits( unsigned ); // prototype14 15 int main()16 {17 unsigned number1 = 960;18 19 // demonstrate bitwise left shift20 cout << "The result of left shifting\n";21 displayBits( number1 );22 cout << "8 bit positions using the left "23 << "shift operator is\n";24 displayBits( number1 << 8 );25

Page 30: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline30

fig18_07.cpp(2 of 3)

26 // demonstrate bitwise right shift27 cout << "\nThe result of right shifting\n";28 displayBits( number1 );29 cout << "8 bit positions using the right "30 << "shift operator is\n";31 displayBits( number1 >> 8 );32 33 return 0;34 35 } // end main36 37 // display bits of an unsigned integer value38 void displayBits( unsigned value )39 {40 const int SHIFT = 8 * sizeof( unsigned ) - 1;41 const unsigned MASK = 1 << SHIFT;42 43 cout << setw( 10 ) << value << " = ";44 45 for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {46 cout << ( value & MASK ? '1' : '0' );47 value <<= 1; // shift value left by 148 49 if ( i % 8 == 0 ) // output a space after 8 bits50 cout << ' ';51 52 } // end for

Page 31: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline31

fig18_07.cpp(3 of 3)

fig18_07.cppoutput (1 of 1)

53 54 cout << endl;55 56 } // end function displayBits

The result of left shifting

960 = 00000000 00000000 00000011 11000000

8 bit positions using the left shift operator is

245760 = 00000000 00000011 11000000 00000000

The result of right shifting

960 = 00000000 00000000 00000011 11000000

8 bit positions using the right shift operator is

3 = 00000000 00000000 00000000 00000011

Page 32: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

32

18.8 Bit Fields

• Bit field – Member of structure whose size (in bits) has been specified

– Enables better memory utilization

– Must be declared int or unsigned– Example

Struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color : 1;};

– Declare with name : width• Bit width must be an integer

Page 33: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

33

18.8 Bit Fields

• Accessing bit fields– Access like any other structure member

Struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color : 1;};

– myCard.face = 10;• face has 4 bits, can store values 0 - 15• suit can store 0 - 3• color can store 0 or 1

Page 34: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline34

fig18_14.cpp(1 of 3)

1 // Fig. 18.14: fig18_14.cpp2 // Representing cards with bit fields in a struct.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 // BitCard structure definition with bit fields13 struct BitCard { 14 unsigned face : 4; // 4 bits; 0-15 15 unsigned suit : 2; // 2 bits; 0-3 16 unsigned color : 1; // 1 bit; 0-1 17 18 }; // end struct BitBard 19 20 void fillDeck( BitCard * const ); // prototype21 void deal( const BitCard * const ); // prototype22 23 int main()24 {25 BitCard deck[ 52 ];26 27 fillDeck( deck );28 deal( deck );

Declare bit fields inside a structure to store card data.

Page 35: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline35

fig18_14.cpp(2 of 3)

29 30 return 0;31 32 } // end main33 34 // initialize BitCards35 void fillDeck( BitCard * const wDeck )36 {37 for ( int i = 0; i <= 51; i++ ) {38 wDeck[ i ].face = i % 13; 39 wDeck[ i ].suit = i / 13; 40 wDeck[ i ].color = i / 26;41 42 } // end for43 44 } // end function fillDeck45

Assign to bit fields as normal, but be careful of each field's range.

Page 36: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline36

fig18_14.cpp(3 of 3)

46 // output cards in two column format; cards 0-25 subscripted 47 // with k1 (column 1); cards 26-51 subscripted k2 (column 2)48 void deal( const BitCard * const wDeck )49 {50 for ( int k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) {51 cout << "Card:" << setw( 3 ) << wDeck[ k1 ].face 52 << " Suit:" << setw( 2 ) << wDeck[ k1 ].suit 53 << " Color:" << setw( 2 ) << wDeck[ k1 ].color 54 << " " << "Card:" << setw( 3 ) << wDeck[ k2 ].face55 << " Suit:" << setw( 2 ) << wDeck[ k2 ].suit 56 << " Color:" << setw( 2 ) << wDeck[ k2 ].color 57 << endl;58 59 } // end for60 61 } // end function deal

Page 37: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline37

fig18_14.cppoutput (1 of 1)

Card: 0 Suit: 0 Color: 0 Card: 0 Suit: 2 Color: 1

Card: 1 Suit: 0 Color: 0 Card: 1 Suit: 2 Color: 1

Card: 2 Suit: 0 Color: 0 Card: 2 Suit: 2 Color: 1

Card: 3 Suit: 0 Color: 0 Card: 3 Suit: 2 Color: 1

Card: 4 Suit: 0 Color: 0 Card: 4 Suit: 2 Color: 1

Card: 5 Suit: 0 Color: 0 Card: 5 Suit: 2 Color: 1

Card: 6 Suit: 0 Color: 0 Card: 6 Suit: 2 Color: 1

Card: 7 Suit: 0 Color: 0 Card: 7 Suit: 2 Color: 1

Card: 8 Suit: 0 Color: 0 Card: 8 Suit: 2 Color: 1

Card: 9 Suit: 0 Color: 0 Card: 9 Suit: 2 Color: 1

Card: 10 Suit: 0 Color: 0 Card: 10 Suit: 2 Color: 1

Card: 11 Suit: 0 Color: 0 Card: 11 Suit: 2 Color: 1

Card: 12 Suit: 0 Color: 0 Card: 12 Suit: 2 Color: 1

Card: 0 Suit: 1 Color: 0 Card: 0 Suit: 3 Color: 1

Card: 1 Suit: 1 Color: 0 Card: 1 Suit: 3 Color: 1

Card: 2 Suit: 1 Color: 0 Card: 2 Suit: 3 Color: 1

Card: 3 Suit: 1 Color: 0 Card: 3 Suit: 3 Color: 1

Card: 4 Suit: 1 Color: 0 Card: 4 Suit: 3 Color: 1

Card: 5 Suit: 1 Color: 0 Card: 5 Suit: 3 Color: 1

Card: 6 Suit: 1 Color: 0 Card: 6 Suit: 3 Color: 1

Card: 7 Suit: 1 Color: 0 Card: 7 Suit: 3 Color: 1

Card: 8 Suit: 1 Color: 0 Card: 8 Suit: 3 Color: 1

Card: 9 Suit: 1 Color: 0 Card: 9 Suit: 3 Color: 1

Card: 10 Suit: 1 Color: 0 Card: 10 Suit: 3 Color: 1

Card: 11 Suit: 1 Color: 0 Card: 11 Suit: 3 Color: 1

Card: 12 Suit: 1 Color: 0 Card: 12 Suit: 3 Color: 1

Page 38: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

38

18.8 Bit Fields

• Other notes– Bit fields are not arrays of bits (cannot use [])

– Cannot take address of bit fields

– Use unnamed bit fields to pad structureStruct Example {unsigned a : 13;unsigned : 3;unsigned b : 4;

};

– Use unnamed, zero-width fields to align to boundaryStruct Example {unsigned a : 13;unsigned : 0;unsigned b : 4;

};

• Automatically aligns b to next boundary

Page 39: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

39

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 40: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

40

18.9 Character-Handling Library

• Upcoming example– isalpha( int c )

• (All character functions take int argument)

• Returns true if c is a letter (A-Z, a-z)

• Returns false otherwise

– isdigit• Returns true if digit (0-9)

– isalnum• Returns true if letter or digit (A-Z, a-z, 0-9)

– isxdigit• Returns true if hexadecimal digit (A-F, a-f, 0-9)

Page 41: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline41

fig18_17.cpp(1 of 2)

1 // Fig. 18.17: fig18_17.cpp2 // Using functions isdigit, isalpha, isalnum and isxdigit.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to isdigit:\n"13 << ( isdigit( '8' ) ? "8 is a" : "8 is not a" ) 14 << " digit\n"15 << ( isdigit( '#' ) ? "# is a" : "# is not a" ) 16 << " digit\n";17 18 cout << "\nAccording to isalpha:\n"19 << ( isalpha( 'A' ) ? "A is a" : "A is not a" ) 20 << " letter\n"21 << ( isalpha( 'b' ) ? "b is a" : "b is not a" ) 22 << " letter\n"23 << ( isalpha( '&' ) ? "& is a" : "& is not a" ) 24 << " letter\n"25 << ( isalpha( '4' ) ? "4 is a" : "4 is not a" ) 26 << " letter\n";27

Note use of conditional operator:

condition ? value if true : value if false

Page 42: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline42

fig18_17.cpp(2 of 2)

28 cout << "\nAccording to isalnum:\n"29 << ( isalnum( 'A' ) ? "A is a" : "A is not a" )30 << " digit or a letter\n"31 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" )32 << " digit or a letter\n"33 << ( isalnum( '#' ) ? "# is a" : "# is not a" )34 << " digit or a letter\n";35 36 cout << "\nAccording to isxdigit:\n"37 << ( isxdigit( 'F' ) ? "F is a" : "F is not a" )38 << " hexadecimal digit\n"39 << ( isxdigit( 'J' ) ? "J is a" : "J is not a" )40 << " hexadecimal digit\n"41 << ( isxdigit( '7' ) ? "7 is a" : "7 is not a" )42 << " hexadecimal digit\n"43 << ( isxdigit( '$' ) ? "$ is a" : "$ is not a" )44 << " hexadecimal digit\n"45 << ( isxdigit( 'f' ) ? "f is a" : "f is not a" )46 << " hexadecimal digit" << endl;47 48 return 0;49 50 } // end main

Page 43: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline43

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 44: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

44

18.9 Character-Handling Library

• Upcoming example– islower

• Returns true if lowercase letter (a-z)

– isupper• Returns true if uppercase letter (A-Z)

– tolower• If passed uppercase letter, returns lowercase letter

– A to a• Otherwise, returns original argument

– toupper• As above, but turns lowercase letter to uppercase

– a to A

Page 45: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline45

fig18_18.cpp(1 of 2)

1 // Fig. 18.18: fig18_18.cpp2 // Using functions islower, isupper, tolower and toupper.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to islower:\n"13 << ( islower( 'p' ) ? "p is a" : "p is not a" ) 14 << " lowercase letter\n"15 << ( islower( 'P' ) ? "P is a" : "P is not a" ) 16 << " lowercase letter\n"17 << ( islower( '5' ) ? "5 is a" : "5 is not a" ) 18 << " lowercase letter\n"19 << ( islower( '!' ) ? "! is a" : "! is not a" ) 20 << " lowercase letter\n";21 22 cout << "\nAccording to isupper:\n"23 << ( isupper( 'D' ) ? "D is an" : "D is not an" ) 24 << " uppercase letter\n"25 << ( isupper( 'd' ) ? "d is an" : "d is not an" ) 26 << " uppercase letter\n"27 << ( isupper( '8' ) ? "8 is an" : "8 is not an" ) 28 << " uppercase letter\n"

Page 46: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline46

fig18_18.cpp(2 of 2)

29 << ( isupper( '$' ) ? "$ is an" : "$ is not an" ) 30 << " uppercase letter\n";31 32 cout << "\nu converted to uppercase is " 33 << static_cast< char >( toupper( 'u' ) )34 << "\n7 converted to uppercase is " 35 << static_cast< char >( toupper( '7' ) )36 << "\n$ converted to uppercase is " 37 << static_cast< char >( toupper( '$' ) )38 << "\nL converted to lowercase is " 39 << static_cast< char >( tolower( 'L' ) ) << endl;40 41 return 0;42 43 } // end main

Page 47: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline47

fig18_18.cppoutput (1 of 1)

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 48: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

48

18.9 Character-Handling Library

• Upcoming example– isspace

• Returns true if space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v'

– iscntrl• Returns true if control character, such as tabs, form feed,

alert ('\a'), backspace('\b'), carriage return, newline

– ispunct• Returns true if printing character other than space, digit, or

letter• $ # ( ) [ ] { } ; : %, etc.

Page 49: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

49

18.9 Character-Handling Library

• Upcoming example– isprint

• Returns true if character can be displayed (including space)

– isgraph• Returns true if character can be displayed, not including

space

Page 50: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline50

fig18_19.cpp(1 of 2)

1 // Fig. 18.19: fig18_19.cpp2 // Using functions isspace, iscntrl, ispunct, isprint, isgraph.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to isspace:\nNewline " 13 << ( isspace( '\n' ) ? "is a" : "is not a" )14 << " whitespace character\nHorizontal tab " 15 << ( isspace( '\t' ) ? "is a" : "is not a" )16 << " whitespace character\n"17 << ( isspace( '%' ) ? "% is a" : "% is not a" )18 << " whitespace character\n";19 20 cout << "\nAccording to iscntrl:\nNewline " 21 << ( iscntrl( '\n' ) ? "is a" : "is not a" )22 << " control character\n"23 << ( iscntrl( '$' ) ? "$ is a" : "$ is not a" )24 << " control character\n";25

Page 51: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline51

fig18_19.cpp(2 of 2)

26 cout << "\nAccording to ispunct:\n"27 << ( ispunct( ';' ) ? "; is a" : "; is not a" )28 << " punctuation character\n"29 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )30 << " punctuation character\n"31 << ( ispunct( '#' ) ? "# is a" : "# is not a" )32 << " punctuation character\n";33 34 cout << "\nAccording to isprint:\n"35 << ( isprint( '$' ) ? "$ is a" : "$ is not a" )36 << " printing character\nAlert " 37 << ( isprint( '\a' ) ? "is a" : "is not a" )38 << " printing character\n";39 40 cout << "\nAccording to isgraph:\n"41 << ( isgraph( 'Q' ) ? "Q is a" : "Q is not a" )42 << " printing character other than a space\nSpace " 43 << ( isgraph( ' ' ) ? "is a" : "is not a" )44 << " printing character other than a space" << endl;45 46 return 0;47 48 } // end main

Page 52: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline52

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 53: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

53

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 54: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

54

18.10 String-Conversion Functions

• 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

Page 55: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline55

fig18_21.cpp(1 of 1)

fig18_21.cppoutput (1 of 1)

1 // Fig. 18.21: fig18_21.cpp2 // Using atof.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atof prototype9 10 int main()11 {12 double d = atof( "99.0" );13 14 cout << "The string \"99.0\" converted to double is "15 << d << "\nThe converted value divided by 2 is "16 << d / 2.0 << endl;17 18 return 0;19 20 } // end main

The string "99.0" converted to double is 99

The converted value divided by 2 is 49.5

Page 56: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline56

fig18_22.cpp(1 of 1)

fig18_22.cppoutput (1 of 1)

1 // Fig. 18.22: fig18_22.cpp2 // Using atoi.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atoi prototype9 10 int main()11 {12 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;17 18 return 0;19 20 } // end main

The string "2593" converted to int is 2593

The converted value minus 593 is 2000

Page 57: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline57

fig18_23.cpp(1 of 1)

fig18_23.cppoutput (1 of 1)

1 // Fig. 18.23: fig18_23.cpp2 // Using atol.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atol prototype9 10 int main()11 {12 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;17 18 return 0;19 20 } // end main

The string "1000000" converted to long int is 1000000

The converted value divided by 2 is 500000

Page 58: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

58

18.10 String-Conversion Functions

• Functions– 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"

Page 59: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline59

fig18_24.cpp(1 of 1)

fig18_24.cppoutput (1 of 1)

1 // Fig. 18.24: fig18_24.cpp2 // Using strtod.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtod prototype9 10 int main()11 {12 double d;13 const char *string1 = "51.2% are admitted";14 char *stringPtr;15 16 d = strtod( string1, &stringPtr );17 18 cout << "The string \"" << string1 19 << "\" is converted to the\ndouble value " << d 20 << " and the string \"" << stringPtr << "\"" << endl;21 22 return 0;23 24 } // end main

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

double value 51.2 and the string "% are admitted"

Page 60: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

60

18.10 String-Conversion Functions

• Functions– 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• As above, with unsigned long

Page 61: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline61

fig18_25.cpp(1 of 1)

1 // Fig. 18.25: fig18_25.cpp2 // Using strtol.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtol prototype9 10 int main()11 {12 long x;13 const char *string1 = "-1234567abc";14 char *remainderPtr;15 16 x = strtol( string1, &remainderPtr, 0 );17 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;24 25 return 0;26 27 } // end main

Page 62: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline62

fig18_25.cppoutput (1 of 1)

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 63: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline63

fig18_26.cpp(1 of 1)

1 // Fig. 18.26: fig18_26.cpp2 // Using strtoul.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtoul prototype9 10 int main()11 {12 unsigned long x;13 const char *string1 = "1234567abc";14 char *remainderPtr;15 16 x = strtoul( string1, &remainderPtr, 0 );17 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;24 25 return 0;26 27 } // end main

Page 64: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline64

fig18_26.cppoutput (1 of 1)

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

Page 65: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

65

18.11 Search Functions of the String-Handling Library

• String handling library– Search strings for characters, other strings

– Type size_t• Defined as integer of type returned by sizeof

Page 66: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

66

18.11 Search Functions of the String-Handling Library

• Functions– char *strchr( const char *s, int c )

• Returns pointer to first occurrence of c in s• Returns NULL if not found

Page 67: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline67

fig18_28.cpp(1 of 2)

1 // Fig. 18.28: fig18_28.cpp2 // Using strchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strchr prototype9 10 int main()11 {12 const char *string1 = "This is a test";13 char character1 = 'a';14 char character2 = 'z';15 16 if ( strchr( string1, character1 ) != NULL )17 cout << '\'' << character1 << "' was found in \""18 << string1 << "\".\n";19 else20 cout << '\'' << character1 << "' was not found in \""21 << string1 << "\".\n";22 23 if ( strchr( string1, character2 ) != NULL )24 cout << '\'' << character2 << "' was found in \""25 << string1 << "\".\n";26 else27 cout << '\'' << character2 << "' was not found in \""28 << string1 << "\"." << endl;

Page 68: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline68

fig18_28.cpp(2 of 2)

fig18_28.cppoutput (1 of 1)

29 30 return 0;31 32 } // end main

'a' was found in "This is a test".

'z' was not found in "This is a test".

Page 69: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

69

18.11 Search Functions of the String-Handling Library

• Functions– size_t strcspn( const char *s1, const char *s2 )

• Returns length of s1 that does not contain characters in s2• Starts from beginning of s1

– char *strpbrk( const char *s1, const char *s2 )

• Finds first occurrence of any character in s2 in s1• Returns NULL if not found

– char *strrchr( const char *s, int c ) • Returns pointer to last occurrence of c in s• Returns NULL if not found

Page 70: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline70

fig18_29.cpp(1 of 1)

fig18_29.cppoutput (1 of 1)

1 // Fig. 18.29: fig18_29.cpp2 // Using strcspn.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strcspn prototype9 10 int main()11 {12 const char *string1 = "The value is 3.14159";13 const char *string2 = "1234567890";14 15 cout << "string1 = " << string1 << "\nstring2 = " << string216 << "\n\nThe length of the initial segment of string1"17 << "\ncontaining no characters from string2 = "18 << strcspn( string1, string2 ) << endl;19 20 return 0;21 22 } // end main

string1 = The value is 3.14159

string2 = 1234567890

The length of the initial segment of string1

containing no characters from string2 = 13

Page 71: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline71

fig18_30.cpp(1 of 1)

fig18_30.cppoutput (1 of 1)

1 // Fig. 18.30: fig18_30.cpp2 // Using strpbrk.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strpbrk prototype9 10 int main()11 {12 const char *string1 = "This is a test";13 const char *string2 = "beware";14 15 cout << "Of the characters in \"" << string2 << "\"\n'"16 << *strpbrk( string1, string2 ) << '\''17 << " is the first character to appear in\n\""18 << string1 << '\"' << endl;19 20 return 0;21 22 } // end main

Of the characters in "beware"

'a' is the first character to appear in

"This is a test"

Page 72: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline72

fig18_31.cpp(1 of 1)

fig18_31.cppoutput (1 of 1)

1 // Fig. 18.31: fig18_31.cpp2 // Using strrchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strrchr prototype9 10 int main()11 {12 const char *string1 = 13 "A zoo has many animals including zebras";14 int c = 'z';15 16 cout << "The remainder of string1 beginning with the\n"17 << "last occurrence of character '" 18 << static_cast< char >( c ) // print as char not int19 << "' is: \"" << strrchr( string1, c ) << '\"' << endl;20 21 return 0;22 23 } // end main

The remainder of string1 beginning with the

last occurrence of character 'z' is: "zebras"

Page 73: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

73

18.11 Search Functions of the String-Handling Library

• Functions– size_t strspn( const char *s1, const char *s2 )

• Returns length of s1 that contains only characters in s2• Starts from beginning of s1

– char *strstr( const char *s1, const char *s2 )

• Finds first occurrence of s2 in s1• Returns NULL if not found

Page 74: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline74

fig18_32.cpp(1 of 1)

1 // Fig. 18.32: fig18_32.cpp2 // Using strspn.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strspn prototype9 10 int main()11 {12 const char *string1 = "The value is 3.14159";13 const char *string2 = "aehils Tuv";14 15 cout << "string1 = " << string1 16 << "\nstring2 = " << string217 << "\n\nThe length of the initial segment of string1\n"18 << "containing only characters from string2 = "19 << strspn( string1, string2 ) << endl;20 21 return 0;22 23 } // end main

Page 75: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline75

fig18_32.cppoutput (1 of 1)

string1 = The value is 3.14159

string2 = aehils Tuv

The length of the initial segment of string1

containing only characters from string2 = 13

Page 76: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline76

fig18_33.cpp(1 of 1)

1 // Fig. 18.33: fig18_33.cpp2 // Using strstr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strstr prototype9 10 int main()11 {12 const char *string1 = "abcdefabcdef";13 const char *string2 = "def";14 15 cout << "string1 = " << string1 << "\nstring2 = " << string216 << "\n\nThe remainder of string1 beginning with the\n"17 << "first occurrence of string2 is: "18 << strstr( string1, string2 ) << endl;19 20 return 0;21 22 } // end main

Page 77: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline77

fig18_33.cppoutput (1 of 1)

string1 = abcdefabcdef

string2 = def

The remainder of string1 beginning with the

first occurrence of string2 is: defabcdef

Page 78: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

78

18.12 Memory Functions of the String-Handling Library

• Memory functions– Treat memory as array of characters

– Manipulate any block of data

– Treat pointers as void *– Specify size (number of bytes)

Page 79: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

79

18.12 Memory Functions of the String-Handling Library

• Functions– void *memcpy( void *s1, const void *s2, size_t n )

• Copies n characters from s2 to s1• Do not use if s2 and s1 overlap

• Returns pointer to result

– void *memmove( void *s1, const void *s2, size_t n )

• Copies n characters from s2 to s1• Ok if objects overlap

• Returns pointer to result

Page 80: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline80

fig18_35.cpp(1 of 1)

fig18_35.cppoutput (1 of 1)

1 // Fig. 18.35: fig18_35.cpp2 // Using memcpy.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memcpy prototype9 10 int main()11 {12 char s1[ 17 ];13 char s2[] = "Copy this string";14 15 memcpy( s1, s2, 17 );16 17 cout << "After s2 is copied into s1 with memcpy,\n"18 << "s1 contains \"" << s1 << '\"' << endl;19 20 return 0;21 22 } // end main

After s2 is copied into s1 with memcpy,

s1 contains "Copy this string"

Page 81: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline81

fig18_36.cpp(1 of 1)

fig18_36.cppoutput (1 of 1)

1 // Fig. 18.36: fig18_36.cpp2 // Using memmove.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memmove prototype9 10 int main()11 {12 char x[] = "Home Sweet Home";13 14 cout << "The string in array x before memmove is: " << x;15 cout << "\nThe string in array x after memmove is: "16 << static_cast< char * >( memmove( x, &x[ 5 ], 10 ) ) 17 << endl;18 19 return 0;20 21 } // end main

The string in array x before memmove is: Home Sweet Home

The string in array x after memmove is: Sweet Home Home

Page 82: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

82

18.12 Memory Functions of the String-Handling Library

• Functions– int memcmp( const void *s1, const void *s2, size_t n )

• Compares first n characters of s1 and s2• Returns

– 0 (equal)

– Greater than 0 (s1 > s2)

– Less than 0 (s1 < s2)

Page 83: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline83

fig18_37.cpp(1 of 1)

1 // Fig. 18.37: fig18_37.cpp2 // Using memcmp.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 #include <cstring> // memcmp prototype13 14 int main()15 {16 char s1[] = "ABCDEFG";17 char s2[] = "ABCDXYZ";18 19 cout << "s1 = " << s1 << "\ns2 = " << s2 << endl20 << "\nmemcmp(s1, s2, 4) = " << setw( 3 ) 21 << memcmp( s1, s2, 4 ) << "\nmemcmp(s1, s2, 7) = " 22 << setw( 3 ) << memcmp( s1, s2, 7 )23 << "\nmemcmp(s2, s1, 7) = " << setw( 3 ) 24 << memcmp( s2, s1, 7 ) << endl;25 26 return 0;27 28 } // end main

Page 84: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline84

fig18_37.cppoutput (1 of 1)

s1 = ABCDEFG

s2 = ABCDXYZ

memcmp(s1, s2, 4) = 0

memcmp(s1, s2, 7) = -1

memcmp(s2, s1, 7) = 1

Page 85: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc. All rights reserved.

85

18.12 Memory Functions of the String-Handling Library

• Functions– void *memchr(const void *s, int c, size_t n )

• Finds first occurrence of c in first n characters of s• Returns pointer to c or NULL

– void *memset( void *s, int c, size_t n )• Copies c into first n characters of s• Returns pointer to result

Page 86: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline86

fig18_38.cpp(1 of 1)

fig18_38.cppoutput (1 of 1)

1 // Fig. 18.38: fig18_38.cpp2 // Using memchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memchr prototype9 10 int main()11 {12 char s[] = "This is a string";13 14 cout << "The remainder of s after character 'r' "15 << "is found is \"" 16 << static_cast< char * >( memchr( s, 'r', 16 ) )17 << '\"' << endl;18 19 return 0;20 21 } // end main

The remainder of s after character 'r' is found is "ring"

Page 87: Chapter 18 - Bits, Characters, Strings  and Structures

2003 Prentice Hall, Inc.All rights reserved.

Outline87

fig18_39.cpp(1 of 1)

fig18_39.cppoutput (1 of 1)

1 // Fig. 18.39: fig18_39.cpp2 // Using memset.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memset prototype9 10 int main()11 {12 char string1[ 15 ] = "BBBBBBBBBBBBBB";13 14 cout << "string1 = " << string1 << endl;15 cout << "string1 after memset = "16 << static_cast< char * >( memset( string1, 'b', 7 ) )17 << endl;18 19 return 0;20 21 } // end main

string1 = BBBBBBBBBBBBBB

string1 after memset = bbbbbbbBBBBBBB