Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 87

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

 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

 2003 Prentice Hall, Inc. All rights reserved.


3

18.2 Structure Definitions

• Structure definition
struct 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

 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 structure
struct Card {
char *face;
char *suit;
} oneCard, deck[ 52 ], *cPtr;

 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"

 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

Byte 0 1 2 3

01100001 00000000 01100001

– Since hole undefined, structures may not compare equally


• Cannot use ==

 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 individually
Card threeHearts;
threeHearts.face = “Three”;
threeHearts.suit = “Hearts”;

 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

 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;

 2003 Prentice Hall, Inc. All rights reserved.


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

 2003 Prentice Hall, Inc. All rights reserved.


11
1 // Fig. 18.2: fig18_02.cpp
2 // Card shuffling and dealing program using structures.
Outline
3 #include <iostream>
4
fig18_02.cpp
5 using std::cout;
(1 of 4)
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
Declare the Card structure.
15 #include <cstdlib>
16 #include <ctime>
In functions, it is used like
17 any other type.
18 // Card structure definition
19 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 );

 2003 Prentice Hall, Inc.


All rights reserved.
12
28
29 int main()
Outline
30 {
31 Card deck[ 52 ];
fig18_02.cpp
32 char *face[] = { "Ace", "Deuce", "Three", "Four",
(2 of 4)
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 main
46

 2003 Prentice Hall, Inc.


All rights reserved.
13
47 // place strings into Card structures
48 void fillDeck( Card * const wDeck, Create every face and suit.
Outline
49 char *wFace[], char *wSuit[] ) Note format for accessing a
50 { data member in an array of
fig18_02.cpp
51 for ( int i = 0; i < 52; i++ ) { structs. (3 of 4)
52 wDeck[ i ].face = wFace[ i % 13 ];
53 wDeck[ i ].suit = wSuit[ i / 13 ];
54
55 } // end for
56
57 } // end function fillDeck
58
Pick a random card in deck
59 // shuffle cards
(0-51) and swap with current
60 void shuffle( Card * const wDeck )
61 {
card. Notice the use of
62 for ( int i = 0; i < 52; i++ ) { structure assignment.
63 int j = rand() % 52;
64 Card temp = wDeck[ i ];
65 wDeck[ i ] = wDeck[ j ];
66 wDeck[ j ] = temp;
67
68 } // end for
69
70 } // end function shuffle
71

 2003 Prentice Hall, Inc.


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

 2003 Prentice Hall, Inc.


All rights reserved.
15
King of Clubs Ten of Diamonds
Five of Diamonds Jack of Clubs
Outline
Seven of Spades Five of Clubs
Three of Spades King of Hearts
fig18_02.cpp
Ten of Clubs Eight of Spades
output (1 of 1)
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

 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

 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

 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

 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

 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)

 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

 2003 Prentice Hall, Inc. All rights reserved.


22
1 // Fig. 18.5: fig18_05.cpp
2 // Printing an unsigned integer in bits.
Outline
3 #include <iostream>
4
5 using std::cout;
fig18_05.cpp
6 using std::cin;
7 using std::endl;
(1 of 2)
8
9 #include <iomanip>
10
11 using std::setw;
12
13 void displayBits( unsigned ); // prototype
14
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 main
26

 2003 Prentice Hall, Inc.


All rights reserved.
23
27 // display bits of an unsigned integer value
28 void displayBits( unsigned value )
Outline
29 {
30 const int SHIFT = 8 * sizeof( unsigned ) - 1;
31 const unsigned MASK = 1 << SHIFT;
fig18_05.cpp
32
33 cout << setw( 10 ) << value << " = ";
(2 of 2)
SHIFT = 32 - 1 = 31
34
35 for ( unsigned i =
MASK = 10000000 00000000 00000000
1; i <= SHIFT + 1; i++ ) {
00000000
fig18_05.cpp
36 cout << ( value& MASK ? '1' : '0' ); output (1 of 1)
37 value <<= 1; // shift value left by 1
Bitwise AND value and
38
39 if ( i % 8 == 0 ) // output a space after 8 bits
mask. If it is nonzero (true),
40 cout << ' '; Shift value left by 1 to then the leftmost digit is a 1.
41 examine next bit. Note use of
42 } // end for <<= (same as
43 value = value << 1).
44 cout << endl;
45
46 } // end function displayBits

Enter an unsigned integer: 65000


65000 = 00000000 00000000 11111101 11101000

 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)

 2003 Prentice Hall, Inc. All rights reserved.


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

 2003 Prentice Hall, Inc.


All rights reserved.
26
23 // demonstrate bitwise &
24 number1 = 2179876355;
Outline
25 mask = 1;
26 cout << "The result of combining the following\n";
fig18_07.cpp
27 displayBits( number1 );
(2 of 4)
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 OR
42 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 );

 2003 Prentice Hall, Inc.


All rights reserved.
27
49
50 // demonstrate bitwise complement
Outline
51 number1 = 21845;
52 cout << "\nThe one's complement of\n";
fig18_07.cpp
53 displayBits( number1 );
(3 of 4)
54 cout << "is" << endl;
55 displayBits( ~number1 );
56
57 return 0;
58
59 } // end main
60
61 // display bits of an unsigned integer value
62 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 1
72
73 if ( i % 8 == 0 ) // output a space after 8 bits
74 cout << ' ';
75
76 } // end for
 2003 Prentice Hall, Inc.
All rights reserved.
28
77
78 cout << endl;
Outline
79
80 } // end function displayBits
fig18_07.cpp
(4 of 4)
The result of combining the following
2179876355 = 10000001 11101110 01000110 00000011
fig18_07.cpp
1 = 00000000 00000000 00000000 00000001
using the bitwise AND operator & is
output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
29
1 // Fig. 18.11: fig18_11.cpp
2 // Using the bitwise shift operators.
Outline
3 #include <iostream>
4
fig18_07.cpp
5 using std::cout;
(1 of 3)
6 using std::cin;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 void displayBits( unsigned ); // prototype
14
15 int main()
16 {
17 unsigned number1 = 960;
18
19 // demonstrate bitwise left shift
20 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

 2003 Prentice Hall, Inc.


All rights reserved.
30
26 // demonstrate bitwise right shift
27 cout << "\nThe result of right shifting\n";
Outline
28 displayBits( number1 );
29 cout << "8 bit positions using the right "
fig18_07.cpp
30 << "shift operator is\n";
(2 of 3)
31 displayBits( number1 >> 8 );
32
33 return 0;
34
35 } // end main
36
37 // display bits of an unsigned integer value
38 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 1
48
49 if ( i % 8 == 0 ) // output a space after 8 bits
50 cout << ' ';
51
52 } // end for

 2003 Prentice Hall, Inc.


All rights reserved.
31
53
54 cout << endl;
Outline
55
56 } // end function displayBits
fig18_07.cpp
(3 of 3)
The result of left shifting
960 = 00000000 00000000 00000011 11000000
fig18_07.cpp
8 bit positions using the left shift operator is
245760 = 00000000 00000011 11000000 00000000
output (1 of 1)

The result of right shifting


960 = 00000000 00000000 00000011 11000000
8 bit positions using the right shift operator is
3 = 00000000 00000000 00000000 00000011

 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

 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

 2003 Prentice Hall, Inc. All rights reserved.


34
1 // Fig. 18.14: fig18_14.cpp
2 // Representing cards with bit fields in a struct.
Outline
3 #include <iostream>
4
fig18_14.cpp
5 using std::cout;
(1 of 3)
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw; Declare bit fields inside a
11 structure to store card data.
12 // BitCard structure definition with bit fields
13 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 ); // prototype
21 void deal( const BitCard * const ); // prototype
22
23 int main()
24 {
25 BitCard deck[ 52 ];
26
27 fillDeck( deck );
28 deal( deck );
 2003 Prentice Hall, Inc.
All rights reserved.
35
29
30 return 0;
Outline
31
32 } // end main
fig18_14.cpp
33
(2 of 3)
34 // initialize BitCards
35 void fillDeck( BitCard * const wDeck ) Assign to bit fields as normal,
36 { but be careful of each field's
37 for ( int i = 0; i <= 51; i++ ) { range.
38 wDeck[ i ].face = i % 13;
39 wDeck[ i ].suit = i / 13;
40 wDeck[ i ].color = i / 26;
41
42 } // end for
43
44 } // end function fillDeck
45

 2003 Prentice Hall, Inc.


All rights reserved.
36
46 // output cards in two column format; cards 0-25 subscripted
47 // with k1 (column 1); cards 26-51 subscripted k2 (column 2)
Outline
48 void deal( const BitCard * const wDeck )
49 {
fig18_14.cpp
50 for ( int k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) {
(3 of 3)
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 ].face
55 << " Suit:" << setw( 2 ) << wDeck[ k2 ].suit
56 << " Color:" << setw( 2 ) << wDeck[ k2 ].color
57 << endl;
58
59 } // end for
60
61 } // end function deal

 2003 Prentice Hall, Inc.


All rights reserved.
37
Card: 0 Suit: 0 Color: 0 Card: 0 Suit: 2 Color: 1
Card: 1 Suit: 0 Color: 0 Card: 1 Suit: 2 Color: 1
Outline
Card: 2 Suit: 0 Color: 0 Card: 2 Suit: 2 Color: 1
Card: 3 Suit: 0 Color: 0 Card: 3 Suit: 2 Color: 1
fig18_14.cpp
Card: 4 Suit: 0 Color: 0 Card: 4 Suit: 2 Color: 1
output (1 of 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

 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 structure
Struct Example {
unsigned a : 13;
unsigned : 3;
unsigned b : 4;
};
– Use unnamed, zero-width fields to align to boundary
Struct Example {
unsigned a : 13;
unsigned : 0;
unsigned b : 4;
};
• Automatically aligns b to next boundary

 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

 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)

 2003 Prentice Hall, Inc. All rights reserved.


41
1 // Fig. 18.17: fig18_17.cpp
2 // Using functions isdigit, isalpha, isalnum and isxdigit.
Outline
3 #include <iostream>
4
fig18_17.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
Note use of conditional operator:
8 #include <cctype> // character-handling function prototypes
9
10 int main() condition ? value if true : value if false
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

 2003 Prentice Hall, Inc.


All rights reserved.
42
28 cout << "\nAccording to isalnum:\n"
29 << ( isalnum( 'A' ) ? "A is a" : "A is not a" )
Outline
30 << " digit or a letter\n"
31 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" )
fig18_17.cpp
32 << " digit or a letter\n"
(2 of 2)
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

 2003 Prentice Hall, Inc.


All rights reserved.
43
According to isdigit:
8 is a digit
Outline
# is not a digit

fig18_17.cpp
According to isalpha:
output (1 of 1)
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

 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

 2003 Prentice Hall, Inc. All rights reserved.


45
1 // Fig. 18.18: fig18_18.cpp
2 // Using functions islower, isupper, tolower and toupper.
Outline
3 #include <iostream>
4
fig18_18.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <cctype> // character-handling function prototypes
9
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"
 2003 Prentice Hall, Inc.
All rights reserved.
46
29 << ( isupper( '$' ) ? "$ is an" : "$ is not an" )
30 << " uppercase letter\n";
Outline
31
32 cout << "\nu converted to uppercase is "
fig18_18.cpp
33 << static_cast< char >( toupper( 'u' ) )
(2 of 2)
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

 2003 Prentice Hall, Inc.


All rights reserved.
47
According to islower:
p is a lowercase letter
Outline
P is not a lowercase letter
5 is not a lowercase letter
fig18_18.cpp
! is not a lowercase letter
output (1 of 1)
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

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

 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

 2003 Prentice Hall, Inc. All rights reserved.


50
1 // Fig. 18.19: fig18_19.cpp
2 // Using functions isspace, iscntrl, ispunct, isprint, isgraph.
Outline
3 #include <iostream>
4
fig18_19.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <cctype> // character-handling function prototypes
9
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

 2003 Prentice Hall, Inc.


All rights reserved.
51
26 cout << "\nAccording to ispunct:\n"
27 << ( ispunct( ';' ) ? "; is a" : "; is not a" )
Outline
28 << " punctuation character\n"
29 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )
fig18_19.cpp
30 << " punctuation character\n"
(2 of 2)
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

 2003 Prentice Hall, Inc.


All rights reserved.
52
According to isspace:
Newline is a whitespace character
Outline
Horizontal tab is a whitespace character
% is not a whitespace character
fig18_19.cpp
output (1 of 1)
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

 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

 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

 2003 Prentice Hall, Inc. All rights reserved.


55
1 // Fig. 18.21: fig18_21.cpp
2 // Using atof.
Outline
3 #include <iostream>
4
fig18_21.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // atof prototype fig18_21.cpp
9 output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.
56
1 // Fig. 18.22: fig18_22.cpp
2 // Using atoi.
Outline
3 #include <iostream>
4
fig18_22.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // atoi prototype fig18_22.cpp
9 output (1 of 1)
10 int main()
11 {
12 int i = atoi( "2593" );
13
14 cout << "The string \"2593\" converted to int is " << i
15 << "\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

 2003 Prentice Hall, Inc.


All rights reserved.
57
1 // Fig. 18.23: fig18_23.cpp
2 // Using atol.
Outline
3 #include <iostream>
4
fig18_23.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // atol prototype fig18_23.cpp
9 output (1 of 1)
10 int main()
11 {
12 long x = atol( "1000000" );
13
14 cout << "The string \"1000000\" converted to long is " << x
15 << "\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

 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"

 2003 Prentice Hall, Inc. All rights reserved.


59
1 // Fig. 18.24: fig18_24.cpp
2 // Using strtod.
Outline
3 #include <iostream>
4
fig18_24.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // strtod prototype fig18_24.cpp
9 output (1 of 1)
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"

 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

 2003 Prentice Hall, Inc. All rights reserved.


61
1 // Fig. 18.25: fig18_25.cpp
2 // Using strtol.
Outline
3 #include <iostream>
4
fig18_25.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // strtol prototype
9
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 \"" << string1
19 << "\"\nThe converted value is " << x
20 << "\nThe remainder of the original string is \""
21 << remainderPtr
22 << "\"\nThe converted value plus 567 is "
23 << x + 567 << endl;
24
25 return 0;
26
27 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
62
The original string is "-1234567abc"
The converted value is -1234567
Outline
The remainder of the original string is "abc"
The converted value plus 567 is -1234000
fig18_25.cpp
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
63
1 // Fig. 18.26: fig18_26.cpp
2 // Using strtoul.
Outline
3 #include <iostream>
4
fig18_26.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstdlib> // strtoul prototype
9
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 \"" << string1
19 << "\"\nThe converted value is " << x
20 << "\nThe remainder of the original string is \""
21 << remainderPtr
22 << "\"\nThe converted value minus 567 is "
23 << x - 567 << endl;
24
25 return 0;
26
27 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
64
The original string is "1234567abc"
The converted value is 1234567
Outline
The remainder of the original string is "abc"
The converted value minus 567 is 1234000
fig18_26.cpp
output (1 of 1)

 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

 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

 2003 Prentice Hall, Inc. All rights reserved.


67
1 // Fig. 18.28: fig18_28.cpp
2 // Using strchr.
Outline
3 #include <iostream>
4
fig18_28.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 #include <cstring> // strchr prototype
9
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 else
20 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 else
27 cout << '\'' << character2 << "' was not found in \""
28 << string1 << "\"." << endl;
 2003 Prentice Hall, Inc.
All rights reserved.
68
29
30 return 0;
Outline
31
32 } // end main
fig18_28.cpp
'a' was found in "This is a test". (2 of 2)
'z' was not found in "This is a test".
fig18_28.cpp
output (1 of 1)

 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

 2003 Prentice Hall, Inc. All rights reserved.


70
1 // Fig. 18.29: fig18_29.cpp
2 // Using strcspn.
Outline
3 #include <iostream>
4
fig18_29.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // strcspn prototype fig18_29.cpp
9 output (1 of 1)
10 int main()
11 {
12 const char *string1 = "The value is 3.14159";
13 const char *string2 = "1234567890";
14
15 cout << "string1 = " << string1 << "\nstring2 = " << string2
16 << "\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
 2003 Prentice Hall, Inc.
All rights reserved.
71
1 // Fig. 18.30: fig18_30.cpp
2 // Using strpbrk.
Outline
3 #include <iostream>
4
fig18_30.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // strpbrk prototype fig18_30.cpp
9 output (1 of 1)
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"

 2003 Prentice Hall, Inc.


All rights reserved.
72
1 // Fig. 18.31: fig18_31.cpp
2 // Using strrchr.
Outline
3 #include <iostream>
4
fig18_31.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // strrchr prototype fig18_31.cpp
9 output (1 of 1)
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 int
19 << "' 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"

 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

 2003 Prentice Hall, Inc. All rights reserved.


74
1 // Fig. 18.32: fig18_32.cpp
2 // Using strspn.
Outline
3 #include <iostream>
4
fig18_32.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // strspn prototype
9
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 = " << string2
17 << "\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

 2003 Prentice Hall, Inc.


All rights reserved.
75
string1 = The value is 3.14159
string2 = aehils Tuv
Outline

The length of the initial segment of string1


fig18_32.cpp
containing only characters from string2 = 13
output (1 of 1)

 2003 Prentice Hall, Inc.


All rights reserved.
76
1 // Fig. 18.33: fig18_33.cpp
2 // Using strstr.
Outline
3 #include <iostream>
4
fig18_33.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // strstr prototype
9
10 int main()
11 {
12 const char *string1 = "abcdefabcdef";
13 const char *string2 = "def";
14
15 cout << "string1 = " << string1 << "\nstring2 = " << string2
16 << "\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

 2003 Prentice Hall, Inc.


All rights reserved.
77
string1 = abcdefabcdef
string2 = def
Outline

The remainder of string1 beginning with the


fig18_33.cpp
first occurrence of string2 is: defabcdef
output (1 of 1)

 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)

 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

 2003 Prentice Hall, Inc. All rights reserved.


80
1 // Fig. 18.35: fig18_35.cpp
2 // Using memcpy.
Outline
3 #include <iostream>
4
fig18_35.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // memcpy prototype fig18_35.cpp
9 output (1 of 1)
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"

 2003 Prentice Hall, Inc.


All rights reserved.
81
1 // Fig. 18.36: fig18_36.cpp
2 // Using memmove.
Outline
3 #include <iostream>
4
fig18_36.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // memmove prototype fig18_36.cpp
9 output (1 of 1)
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

 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)

 2003 Prentice Hall, Inc. All rights reserved.


83
1 // Fig. 18.37: fig18_37.cpp
2 // Using memcmp.
Outline
3 #include <iostream>
4
fig18_37.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <iomanip>
9
10 using std::setw;
11
12 #include <cstring> // memcmp prototype
13
14 int main()
15 {
16 char s1[] = "ABCDEFG";
17 char s2[] = "ABCDXYZ";
18
19 cout << "s1 = " << s1 << "\ns2 = " << s2 << endl
20 << "\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
 2003 Prentice Hall, Inc.
All rights reserved.
84
s1 = ABCDEFG
s2 = ABCDXYZ
Outline

memcmp(s1, s2, 4) = 0
fig18_37.cpp
memcmp(s1, s2, 7) = -1
output (1 of 1)
memcmp(s2, s1, 7) = 1

 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

 2003 Prentice Hall, Inc. All rights reserved.


86
1 // Fig. 18.38: fig18_38.cpp
2 // Using memchr.
Outline
3 #include <iostream>
4
fig18_38.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // memchr prototype fig18_38.cpp
9 output (1 of 1)
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"

 2003 Prentice Hall, Inc.


All rights reserved.
87
1 // Fig. 18.39: fig18_39.cpp
2 // Using memset.
Outline
3 #include <iostream>
4
fig18_39.cpp
5 using std::cout;
(1 of 1)
6 using std::endl;
7
8 #include <cstring> // memset prototype fig18_39.cpp
9 output (1 of 1)
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

 2003 Prentice Hall, Inc.


All rights reserved.

You might also like