Transcript Document

Chapter 18 - Bits, Characters, Strings
and Structures
Outline
18.1
18.2
18.3
18.4
18.5
18.6
18.7
18.8
18.9
18.10
18.11
18.12
Introduction
Structure Definitions
Initializing Structures
Using Structures with Functions
typedef
Example: High-Performance Card-Shuffling and Dealing
Simulation
Bitwise Operators
Bit Fields
Character-Handling Library
String-Conversion Functions
Search Functions of the String-Handling Library
Memory Functions of the String-Handling Library
 2003 Prentice Hall, Inc. All rights reserved.
1
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
01100001
1
2
3
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 CardShuffling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 18.2: fig18_02.cpp
// Card shuffling and dealing program using structures.
#include <iostream>
using
using
using
using
using
11
Outline
fig18_02.cpp
(1 of 4)
std::cout;
std::cin;
std::endl;
std::left;
std::right;
#include <iomanip>
using std::setw;
#include <cstdlib>
#include <ctime>
Declare the Card structure.
In functions, it is used like
any other type.
// Card structure definition
struct Card {
char *face;
char *suit;
}; // end structure Card
void fillDeck( Card * const, char *[], char *[] );
void shuffle( Card * const );
void deal( Card * const );
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
12
int main()
{
Card deck[ 52 ];
char *face[] = { "Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King" };
char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
srand( time( 0 ) );
Outline
fig18_02.cpp
(2 of 4)
// randomize
fillDeck( deck, face, suit );
shuffle( deck );
deal( deck );
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// place strings into Card structures
void fillDeck( Card * const wDeck,
char *wFace[], char *wSuit[] )
{
for ( int i = 0; i < 52; i++ ) {
wDeck[ i ].face = wFace[ i % 13 ];
wDeck[ i ].suit = wSuit[ i / 13 ];
13
Outline
Create every face and suit.
Note format for accessing a
data member in an array
of
fig18_02.cpp
structs.
(3 of 4)
} // end for
} // end function fillDeck
// shuffle cards
void shuffle( Card * const wDeck )
{
for ( int i = 0; i < 52; i++ ) {
int j = rand() % 52;
Card temp = wDeck[ i ];
wDeck[ i ] = wDeck[ j ];
wDeck[ j ] = temp;
Pick a random card in deck
(0-51) and swap with current
card. Notice the use of
structure assignment.
} // end for
} // end function shuffle
 2003 Prentice Hall, Inc.
All rights reserved.
72
73
74
75
76
77
78
79
80
// deal cards
void deal( Card * const wDeck )
{
for ( int i = 0; i < 52; i++ )
cout << right << setw( 5 ) << wDeck[ i ].face << " of "
<< left << setw( 8 ) << wDeck[ i ].suit
<< ( ( i + 1 ) % 2 ? '\t' : '\n' );
14
Outline
fig18_02.cpp
(4 of 4)
} // end function deal
 2003 Prentice Hall, Inc.
All rights reserved.
King
Five
Seven
Three
Ten
Eight
Nine
Three
Six
Seven
Jack
Deuce
Three
Eight
Deuce
Ten
Ten
Queen
Seven
Deuce
Three
Deuce
Four
Nine
Ace
Four
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
Clubs
Diamonds
Spades
Spades
Clubs
Hearts
Diamonds
Diamonds
Clubs
Diamonds
Spades
Diamonds
Clubs
Clubs
Spades
Spades
Hearts
Diamonds
Clubs
Clubs
Hearts
Hearts
Hearts
Spades
Spades
Spades
Ten
Jack
Five
King
Eight
Six
Nine
Queen
Seven
Jack
King
Four
Five
Ace
Ace
Eight
Six
Nine
Queen
Queen
Five
Jack
Ace
Four
Six
King
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
Diamonds
Clubs
Clubs
Hearts
Spades
Hearts
Clubs
Hearts
Hearts
Diamonds
Diamonds
Clubs
Hearts
Hearts
Clubs
Diamonds
Spades
Hearts
Clubs
Spades
Spades
Hearts
Diamonds
Diamonds
Diamonds
Spades
15
Outline
fig18_02.cpp
output (1 of 1)
 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 18.5: fig18_05.cpp
// Printing an unsigned integer in bits.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
22
Outline
fig18_05.cpp
(1 of 2)
#include <iomanip>
using std::setw;
void displayBits( unsigned );
// prototype
int main()
{
unsigned inputValue;
cout << "Enter an unsigned integer: ";
cin >> inputValue;
displayBits( inputValue );
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// display bits of an unsigned integer value
void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw( 10 ) << value << " = ";
23
Outline
fig18_05.cpp
(2 of 2)
SHIFT = 32 - 1 = 31
MASK = 10000000 00000000 00000000
00000000
fig18_05.cpp
1; i <= SHIFT + 1; i++ ) {
& MASK ? '1' : '0' );
output (1 of 1)
for ( unsigned i =
cout << ( value
value <<= 1; // shift value left by 1
if ( i % 8 == 0 )
cout << ' ';
} // end for
// output a space after 8 bits
Shift value left by 1 to
examine next bit. Note use of
<<= (same as
value = value << 1).
Bitwise AND value and
mask. If it is nonzero (true),
then the leftmost digit is a 1.
cout << endl;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Fig. 18.7: fig18_07.cpp
// Using the bitwise AND, bitwise inclusive OR, bitwise
// exclusive OR and bitwise complement operators.
#include <iostream>
25
Outline
fig18_07.cpp
(1 of 4)
using std::cout;
using std::cin;
#include <iomanip>
using std::endl;
using std::setw;
void displayBits( unsigned );
int main()
{
unsigned
unsigned
unsigned
unsigned
// prototype
number1;
number2;
mask;
setBits;
 2003 Prentice Hall, Inc.
All rights reserved.
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// demonstrate bitwise &
number1 = 2179876355;
mask = 1;
cout << "The result of combining the following\n";
displayBits( number1 );
displayBits( mask );
cout << "using the bitwise AND operator & is\n";
displayBits( number1 & mask );
26
Outline
fig18_07.cpp
(2 of 4)
// demonstrate bitwise |
number1 = 15;
setBits = 241;
cout << "\nThe result of combining the following\n";
displayBits( number1 );
displayBits( setBits );
cout << "using the bitwise inclusive OR operator | is\n";
displayBits( number1 | setBits );
// demonstrate bitwise exclusive OR
number1 = 139;
number2 = 199;
cout << "\nThe result of combining the following\n";
displayBits( number1 );
displayBits( number2 );
cout << "using the bitwise exclusive OR operator ^ is\n";
displayBits( number1 ^ number2 );
 2003 Prentice Hall, Inc.
All rights reserved.
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
27
// demonstrate bitwise complement
number1 = 21845;
cout << "\nThe one's complement of\n";
displayBits( number1 );
cout << "is" << endl;
displayBits( ~number1 );
Outline
fig18_07.cpp
(3 of 4)
return 0;
} // end main
// display bits of an unsigned integer value
void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw( 10 ) << value << " = ";
for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {
cout << ( value & MASK ? '1' : '0' );
value <<= 1; // shift value left by 1
if ( i % 8 == 0 )
cout << ' ';
// output a space after 8 bits
} // end for
 2003 Prentice Hall, Inc.
All rights reserved.
77
78
79
80
28
Outline
cout << endl;
} // 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
241 = 00000000 00000000 00000000
using the bitwise inclusive OR operator
255 = 00000000 00000000 00000000
00001111
11110001
| is
11111111
The result of combining the following
139 = 00000000 00000000 00000000
199 = 00000000 00000000 00000000
using the bitwise exclusive OR operator
76 = 00000000 00000000 00000000
10001011
11000111
^ is
01001100
fig18_07.cpp
(4 of 4)
fig18_07.cpp
output (1 of 1)
The one's complement of
21845 = 00000000 00000000 01010101 01010101
is
4294945450 = 11111111 11111111 10101010 10101010
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 18.11: fig18_11.cpp
// Using the bitwise shift operators.
#include <iostream>
29
Outline
fig18_07.cpp
(1 of 3)
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;
void displayBits( unsigned );
// prototype
int main()
{
unsigned number1 = 960;
// demonstrate bitwise left shift
cout << "The result of left shifting\n";
displayBits( number1 );
cout << "8 bit positions using the left "
<< "shift operator is\n";
displayBits( number1 << 8 );
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// demonstrate bitwise right shift
cout << "\nThe result of right shifting\n";
displayBits( number1 );
cout << "8 bit positions using the right "
<< "shift operator is\n";
displayBits( number1 >> 8 );
30
Outline
fig18_07.cpp
(2 of 3)
return 0;
} // end main
// display bits of an unsigned integer value
void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw( 10 ) << value << " = ";
for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {
cout << ( value & MASK ? '1' : '0' );
value <<= 1; // shift value left by 1
if ( i % 8 == 0 )
cout << ' ';
// output a space after 8 bits
} // end for
 2003 Prentice Hall, Inc.
All rights reserved.
53
54
55
56
31
cout << endl;
} // 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
Outline
fig18_07.cpp
(3 of 3)
fig18_07.cpp
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 18.14: fig18_14.cpp
// Representing cards with bit fields in a struct.
#include <iostream>
34
Outline
fig18_14.cpp
(1 of 3)
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
Declare bit fields inside a
structure to store card data.
// BitCard structure definition with bit fields
struct BitCard {
unsigned face : 4;
// 4 bits; 0-15
unsigned suit : 2;
// 2 bits; 0-3
unsigned color : 1; // 1 bit; 0-1
}; // end struct BitBard
void fillDeck( BitCard * const );
void deal( const BitCard * const );
// prototype
// prototype
int main()
{
BitCard deck[ 52 ];
fillDeck( deck );
deal( deck );
 2003 Prentice Hall, Inc.
All rights reserved.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
35
return 0;
} // end main
// initialize BitCards
void fillDeck( BitCard * const wDeck )
{
for ( int i = 0; i <= 51; i++ ) {
wDeck[ i ].face = i % 13;
wDeck[ i ].suit = i / 13;
wDeck[ i ].color = i / 26;
Outline
fig18_14.cpp
(2 of 3)
Assign to bit fields as normal,
but be careful of each field's
range.
} // end for
} // end function fillDeck
 2003 Prentice Hall, Inc.
All rights reserved.
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// output cards in two column format; cards 0-25 subscripted
// with k1 (column 1); cards 26-51 subscripted k2 (column 2)
void deal( const BitCard * const wDeck )
{
for ( int k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) {
cout << "Card:" << setw( 3 ) << wDeck[ k1 ].face
<< " Suit:" << setw( 2 ) << wDeck[ k1 ].suit
<< " Color:" << setw( 2 ) << wDeck[ k1 ].color
<< "
" << "Card:" << setw( 3 ) << wDeck[ k2 ].face
<< " Suit:" << setw( 2 ) << wDeck[ k2 ].suit
<< " Color:" << setw( 2 ) << wDeck[ k2 ].color
<< endl;
36
Outline
fig18_14.cpp
(3 of 3)
} // end for
} // end function deal
 2003 Prentice Hall, Inc.
All rights reserved.
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
0
1
2
3
4
5
6
7
8
9
10
11
12
0
1
2
3
4
5
6
7
8
9
10
11
12
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
Card:
0
1
2
3
4
5
6
7
8
9
10
11
12
0
1
2
3
4
5
6
7
8
9
10
11
12
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
Suit:
2
2
2
2
2
2
2
2
2
2
2
2
2
3
3
3
3
3
3
3
3
3
3
3
3
3
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
Color:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
37
Outline
fig18_14.cpp
output (1 of 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 :
unsigned
:
unsigned b :
};
{
13;
3;
4;
– Use unnamed, zero-width fields to align to boundary
Struct Example
unsigned a :
unsigned
:
unsigned b :
};
{
13;
0;
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 18.17: fig18_17.cpp
// Using functions isdigit, isalpha, isalnum and isxdigit.
#include <iostream>
int main()
{
cout <<
<<
<<
<<
<<
cout <<
<<
<<
<<
<<
<<
<<
<<
<<
Outline
fig18_17.cpp
(1 of 2)
using std::cout;
using std::endl;
#include <cctype>
41
Note use of conditional operator:
// character-handling function prototypes
condition ? value if true : value if false
"According to isdigit:\n"
( isdigit( '8' ) ? "8 is a" : "8 is not a" )
" digit\n"
( isdigit( '#' ) ? "# is a" : "# is not a" )
" digit\n";
"\nAccording to isalpha:\n"
( isalpha( 'A' ) ? "A is a"
" letter\n"
( isalpha( 'b' ) ? "b is a"
" letter\n"
( isalpha( '&' ) ? "& is a"
" letter\n"
( isalpha( '4' ) ? "4 is a"
" letter\n";
: "A is not a" )
: "b is not a" )
: "& is not a" )
: "4 is not a" )
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
cout <<
<<
<<
<<
<<
<<
<<
"\nAccording to isalnum:\n"
( isalnum( 'A' ) ? "A is a" : "A is not a" )
" digit or a letter\n"
( isalnum( '8' ) ? "8 is a" : "8 is not a" )
" digit or a letter\n"
( isalnum( '#' ) ? "# is a" : "# is not a" )
" digit or a letter\n";
cout <<
<<
<<
<<
<<
<<
<<
<<
<<
<<
<<
"\nAccording to isxdigit:\n"
( isxdigit( 'F' ) ? "F is a" :
" hexadecimal digit\n"
( isxdigit( 'J' ) ? "J is a" :
" hexadecimal digit\n"
( isxdigit( '7' ) ? "7 is a" :
" hexadecimal digit\n"
( isxdigit( '$' ) ? "$ is a" :
" hexadecimal digit\n"
( isxdigit( 'f' ) ? "f is a" :
" hexadecimal digit" << endl;
42
Outline
fig18_17.cpp
(2 of 2)
"F is not a" )
"J is not a" )
"7 is not a" )
"$ is not a" )
"f is not a" )
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
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
43
Outline
fig18_17.cpp
output (1 of 1)
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 18.18: fig18_18.cpp
// Using functions islower, isupper, tolower and toupper.
#include <iostream>
int main()
{
cout <<
<<
<<
<<
<<
<<
<<
<<
<<
cout <<
<<
<<
<<
<<
<<
<<
Outline
fig18_18.cpp
(1 of 2)
using std::cout;
using std::endl;
#include <cctype>
45
// character-handling function prototypes
"According to islower:\n"
( islower( 'p' ) ? "p is a"
" lowercase letter\n"
( islower( 'P' ) ? "P is a"
" lowercase letter\n"
( islower( '5' ) ? "5 is a"
" lowercase letter\n"
( islower( '!' ) ? "! is a"
" lowercase letter\n";
: "p is not a" )
: "P is not a" )
: "5 is not a" )
: "! is not a" )
"\nAccording to isupper:\n"
( isupper( 'D' ) ? "D is an" : "D is not an" )
" uppercase letter\n"
( isupper( 'd' ) ? "d is an" : "d is not an" )
" uppercase letter\n"
( isupper( '8' ) ? "8 is an" : "8 is not an" )
" uppercase letter\n"
 2003 Prentice Hall, Inc.
All rights reserved.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<< ( isupper( '$' ) ? "$ is an" : "$ is not an" )
<< " uppercase letter\n";
cout <<
<<
<<
<<
<<
<<
<<
<<
"\nu converted to
static_cast< char
"\n7 converted to
static_cast< char
"\n$ converted to
static_cast< char
"\nL converted to
static_cast< char
uppercase is "
>( toupper( 'u'
uppercase is "
>( toupper( '7'
uppercase is "
>( toupper( '$'
lowercase is "
>( tolower( 'L'
) )
46
Outline
fig18_18.cpp
(2 of 2)
) )
) )
) ) << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
47
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
Outline
fig18_18.cpp
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
7
$
L
converted
converted
converted
converted
to
to
to
to
uppercase
uppercase
uppercase
lowercase
is
is
is
is
U
7
$
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 18.19: fig18_19.cpp
// Using functions isspace, iscntrl, ispunct, isprint, isgraph.
#include <iostream>
Outline
fig18_19.cpp
(1 of 2)
using std::cout;
using std::endl;
#include <cctype>
50
// character-handling function prototypes
int main()
{
cout <<
<<
<<
<<
<<
<<
<<
"According to isspace:\nNewline "
( isspace( '\n' ) ? "is a" : "is not a" )
" whitespace character\nHorizontal tab "
( isspace( '\t' ) ? "is a" : "is not a" )
" whitespace character\n"
( isspace( '%' ) ? "% is a" : "% is not a" )
" whitespace character\n";
cout <<
<<
<<
<<
<<
"\nAccording to iscntrl:\nNewline "
( iscntrl( '\n' ) ? "is a" : "is not a" )
" control character\n"
( iscntrl( '$' ) ? "$ is a" : "$ is not a" )
" control character\n";
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
cout <<
<<
<<
<<
<<
<<
<<
"\nAccording to ispunct:\n"
( ispunct( ';' ) ? "; is a" : "; is not a" )
" punctuation character\n"
( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )
" punctuation character\n"
( ispunct( '#' ) ? "# is a" : "# is not a" )
" punctuation character\n";
cout <<
<<
<<
<<
<<
"\nAccording to isprint:\n"
( isprint( '$' ) ? "$ is a" : "$ is not a" )
" printing character\nAlert "
( isprint( '\a' ) ? "is a" : "is not a" )
" printing character\n";
cout <<
<<
<<
<<
<<
"\nAccording to isgraph:\n"
( isgraph( 'Q' ) ? "Q is a" : "Q is not a" )
" printing character other than a space\nSpace "
( isgraph( ' ' ) ? "is a" : "is not a" )
" printing character other than a space" << endl;
51
Outline
fig18_19.cpp
(2 of 2)
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
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
52
Outline
fig18_19.cpp
output (1 of 1)
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 18.21: fig18_21.cpp
// Using atof.
#include <iostream>
Outline
fig18_21.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
55
// atof prototype
fig18_21.cpp
output (1 of 1)
int main()
{
double d = atof( "99.0" );
cout << "The string \"99.0\" converted to double is "
<< d << "\nThe converted value divided by 2 is "
<< d / 2.0 << endl;
return 0;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 18.22: fig18_22.cpp
// Using atoi.
#include <iostream>
Outline
fig18_22.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
56
// atoi prototype
fig18_22.cpp
output (1 of 1)
int main()
{
int i = atoi( "2593" );
cout << "The string \"2593\" converted to int is " << i
<< "\nThe converted value minus 593 is " << i - 593
<< endl;
return 0;
} // end main
The string "2593" converted to int is 2593
The converted value minus 593 is 2000
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 18.23: fig18_23.cpp
// Using atol.
#include <iostream>
Outline
fig18_23.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
57
// atol prototype
fig18_23.cpp
output (1 of 1)
int main()
{
long x = atol( "1000000" );
cout << "The string \"1000000\" converted to long is " << x
<< "\nThe converted value divided by 2 is " << x / 2
<< endl;
return 0;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 18.24: fig18_24.cpp
// Using strtod.
#include <iostream>
Outline
fig18_24.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
59
// strtod prototype
fig18_24.cpp
output (1 of 1)
int main()
{
double d;
const char *string1 = "51.2% are admitted";
char *stringPtr;
d = strtod( string1, &stringPtr );
cout << "The string \"" << string1
<< "\" is converted to the\ndouble value " << d
<< " and the string \"" << stringPtr << "\"" << endl;
return 0;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 18.25: fig18_25.cpp
// Using strtol.
#include <iostream>
Outline
fig18_25.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
61
// strtol prototype
int main()
{
long x;
const char *string1 = "-1234567abc";
char *remainderPtr;
x = strtol( string1, &remainderPtr, 0 );
cout <<
<<
<<
<<
<<
<<
"The original string is \"" << string1
"\"\nThe converted value is " << x
"\nThe remainder of the original string is \""
remainderPtr
"\"\nThe converted value plus 567 is "
x + 567 << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
The
The
The
The
original string is "-1234567abc"
converted value is -1234567
remainder of the original string is "abc"
converted value plus 567 is -1234000
62
Outline
fig18_25.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 18.26: fig18_26.cpp
// Using strtoul.
#include <iostream>
Outline
fig18_26.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstdlib>
63
// strtoul prototype
int main()
{
unsigned long x;
const char *string1 = "1234567abc";
char *remainderPtr;
x = strtoul( string1, &remainderPtr, 0 );
cout <<
<<
<<
<<
<<
<<
"The original string is \"" << string1
"\"\nThe converted value is " << x
"\nThe remainder of the original string is \""
remainderPtr
"\"\nThe converted value minus 567 is "
x - 567 << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
The
The
The
The
original string is "1234567abc"
converted value is 1234567
remainder of the original string is "abc"
converted value minus 567 is 1234000
64
Outline
fig18_26.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
65
18.11 Search Functions of the StringHandling 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 StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 18.28: fig18_28.cpp
// Using strchr.
#include <iostream>
Outline
fig18_28.cpp
(1 of 2)
using std::cout;
using std::endl;
#include <cstring>
67
// strchr prototype
int main()
{
const char *string1 = "This is a test";
char character1 = 'a';
char character2 = 'z';
if ( strchr( string1, character1 ) != NULL )
cout << '\'' << character1 << "' was found in \""
<< string1 << "\".\n";
else
cout << '\'' << character1 << "' was not found in \""
<< string1 << "\".\n";
if ( strchr( string1, character2 ) != NULL )
cout << '\'' << character2 << "' was found in \""
<< string1 << "\".\n";
else
cout << '\'' << character2 << "' was not found in \""
<< string1 << "\"." << endl;
 2003 Prentice Hall, Inc.
All rights reserved.
29
30
31
32
68
return 0;
} // end main
'a' was found in "This is a test".
'z' was not found in "This is a test".
Outline
fig18_28.cpp
(2 of 2)
fig18_28.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
69
18.11 Search Functions of the StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Fig. 18.29: fig18_29.cpp
// Using strcspn.
#include <iostream>
Outline
fig18_29.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
70
// strcspn prototype
fig18_29.cpp
output (1 of 1)
int main()
{
const char *string1 = "The value is 3.14159";
const char *string2 = "1234567890";
cout <<
<<
<<
<<
"string1 = " << string1 << "\nstring2 = " << string2
"\n\nThe length of the initial segment of string1"
"\ncontaining no characters from string2 = "
strcspn( string1, string2 ) << endl;
return 0;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Fig. 18.30: fig18_30.cpp
// Using strpbrk.
#include <iostream>
Outline
fig18_30.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
71
// strpbrk prototype
fig18_30.cpp
output (1 of 1)
int main()
{
const char *string1 = "This is a test";
const char *string2 = "beware";
cout <<
<<
<<
<<
"Of the characters in \"" << string2 << "\"\n'"
*strpbrk( string1, string2 ) << '\''
" is the first character to appear in\n\""
string1 << '\"' << endl;
return 0;
} // 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 18.31: fig18_31.cpp
// Using strrchr.
#include <iostream>
Outline
fig18_31.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
72
// strrchr prototype
fig18_31.cpp
output (1 of 1)
int main()
{
const char *string1 =
"A zoo has many animals including zebras";
int c = 'z';
cout <<
<<
<<
<<
"The remainder of string1 beginning with the\n"
"last occurrence of character '"
static_cast< char >( c ) // print as char not int
"' is: \"" << strrchr( string1, c ) << '\"' << endl;
return 0;
} // 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 StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 18.32: fig18_32.cpp
// Using strspn.
#include <iostream>
Outline
fig18_32.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
74
// strspn prototype
int main()
{
const char *string1 = "The value is 3.14159";
const char *string2 = "aehils Tuv";
cout <<
<<
<<
<<
<<
"string1 = " << string1
"\nstring2 = " << string2
"\n\nThe length of the initial segment of string1\n"
"containing only characters from string2 = "
strspn( string1, string2 ) << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
string1 = The value is 3.14159
string2 = aehils Tuv
The length of the initial segment of string1
containing only characters from string2 = 13
75
Outline
fig18_32.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Fig. 18.33: fig18_33.cpp
// Using strstr.
#include <iostream>
Outline
fig18_33.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
76
// strstr prototype
int main()
{
const char *string1 = "abcdefabcdef";
const char *string2 = "def";
cout <<
<<
<<
<<
"string1 = " << string1 << "\nstring2 = " << string2
"\n\nThe remainder of string1 beginning with the\n"
"first occurrence of string2 is: "
strstr( string1, string2 ) << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
string1 = abcdefabcdef
string2 = def
The remainder of string1 beginning with the
first occurrence of string2 is: defabcdef
77
Outline
fig18_33.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
78
18.12 Memory Functions of the StringHandling 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 StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Fig. 18.35: fig18_35.cpp
// Using memcpy.
#include <iostream>
Outline
fig18_35.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
80
// memcpy prototype
fig18_35.cpp
output (1 of 1)
int main()
{
char s1[ 17 ];
char s2[] = "Copy this string";
memcpy( s1, s2, 17 );
cout << "After s2 is copied into s1 with memcpy,\n"
<< "s1 contains \"" << s1 << '\"' << endl;
return 0;
} // end main
After s2 is copied into s1 with memcpy,
s1 contains "Copy this string"
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 18.36: fig18_36.cpp
// Using memmove.
#include <iostream>
Outline
fig18_36.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
81
// memmove prototype
fig18_36.cpp
output (1 of 1)
int main()
{
char x[] = "Home Sweet Home";
cout << "The string in array x before memmove is: " << x;
cout << "\nThe string in array x after memmove is: "
<< static_cast< char * >( memmove( x, &x[ 5 ], 10 ) )
<< endl;
return 0;
} // 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 StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 18.37: fig18_37.cpp
// Using memcmp.
#include <iostream>
83
Outline
fig18_37.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <cstring>
// memcmp prototype
int main()
{
char s1[] = "ABCDEFG";
char s2[] = "ABCDXYZ";
cout <<
<<
<<
<<
<<
<<
"s1 = " << s1 << "\ns2 = " << s2 << endl
"\nmemcmp(s1, s2, 4) = " << setw( 3 )
memcmp( s1, s2, 4 ) << "\nmemcmp(s1, s2, 7) = "
setw( 3 ) << memcmp( s1, s2, 7 )
"\nmemcmp(s2, s1, 7) = " << setw( 3 )
memcmp( s2, s1, 7 ) << endl;
return 0;
} // end main
 2003 Prentice Hall, Inc.
All rights reserved.
s1 = ABCDEFG
s2 = ABCDXYZ
memcmp(s1, s2, 4) =
0
memcmp(s1, s2, 7) = -1
memcmp(s2, s1, 7) = 1
84
Outline
fig18_37.cpp
output (1 of 1)
 2003 Prentice Hall, Inc.
All rights reserved.
85
18.12 Memory Functions of the StringHandling 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 18.38: fig18_38.cpp
// Using memchr.
#include <iostream>
Outline
fig18_38.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
86
// memchr prototype
fig18_38.cpp
output (1 of 1)
int main()
{
char s[] = "This is a string";
cout <<
<<
<<
<<
"The remainder of s after character 'r' "
"is found is \""
static_cast< char * >( memchr( s, 'r', 16 ) )
'\"' << endl;
return 0;
} // end main
The remainder of s after character 'r' is found is "ring"
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 18.39: fig18_39.cpp
// Using memset.
#include <iostream>
Outline
fig18_39.cpp
(1 of 1)
using std::cout;
using std::endl;
#include <cstring>
87
// memset prototype
fig18_39.cpp
output (1 of 1)
int main()
{
char string1[ 15 ] = "BBBBBBBBBBBBBB";
cout << "string1 = " << string1 << endl;
cout << "string1 after memset = "
<< static_cast< char * >( memset( string1, 'b', 7 ) )
<< endl;
return 0;
} // end main
string1 = BBBBBBBBBBBBBB
string1 after memset = bbbbbbbBBBBBBB
 2003 Prentice Hall, Inc.
All rights reserved.