Download - 2006 Pearson Education, Inc. All rights reserved. 1 22 Bits, Characters, C-Strings and struct s
2
2006 Pearson Education, Inc. All rights reserved.
The same old charitable lie Repeated as the years scoot by Perpetually makes a hit—“You really haven’t changed a bit!”
— Margaret Fishback
Vigorous writing is concise. A sentence shouldcontain no unnecessary words, a paragraph no unnecessary sentences.
— William Strunk, Jr.
The chief defect of Henry King Was chewing little bits of string.
— Hilaire Belloc
3
2006 Pearson Education, Inc. All rights reserved.
OBJECTIVESIn this chapter you will learn: To create and use structs. To pass structs to functions by value and by reference. To use typedef to create aliases for previously defined
data types and structs. To manipulate data with the bitwise operators and to
create bit fields for storing data compactly. To use the functions of the character- handling library <cctype>.
To use the string-conversion functions of the general-utilities library <cstdlib>.
To use the string-processing functions of the string-handling library <cstring>.
4
2006 Pearson Education, Inc. All rights reserved.
22.1 Introduction
22.2 Structure Definitions
22.3 Initializing Structures
22.4 Using Structures with Functions
22.5 typedef
22.6 Example: High-Performance Card Shuffling and Dealing Simulation
22.7 Bitwise Operators
22.8 Bit Fields
22.9 Character-Handling Library
22.10 Pointer-Based String-Conversion Functions
22.11 Search Functions of the Pointer-Based String-Handling Library
22.12 Memory Functions of the Pointer-Based String-Handling Library
22.13 Wrap-Up
5
2006 Pearson Education, Inc. All rights reserved.
22.1 Introduction
• Structures– Similar to classes
• Can contain access specifiers, member functions, constructors and destructors
• Only difference is that structure members are public by default (class members are private by default)
• Bitfields– Can specify the exact number of bits to use for a variable
• C-style string manipulation functions– Process blocks of memory as arrays of bytes
6
2006 Pearson Education, Inc. All rights reserved.
22.2 Structure Definitions
• Structures– Aggregate data types
• Built using elements of several types
7
2006 Pearson Education, Inc. All rights reserved.
22.2 Structure Definitions (Cont.)
• Structures (Cont.)– Example
• struct Card{ char *face; char *suit;};
– Keyword struct
– Structure name Card• Used to declare variables of the structure type
– Data members face and suit
• Must have unique names
– Ending semicolon
8
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.1
Forgetting the semicolon that terminates a structure definition is a syntax error.
9
2006 Pearson Education, Inc. All rights reserved.
22.2 Structure Definitions (Cont.)
• Structures (Cont.)– Structure cannot contain an instance of itself
• Can contain a pointer to an instance of itself (self-referential)
– Can declare variables of the structure in the structure definition
• Comma-separated list of variable names between closing brace and semicolon
– Structure name is optional• Variables of unnamed structures can be declared only by
placing them after structure definition, before semicolon
10
2006 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 22.1
Provide a structure name when creating a structure type. The structure name is required for declaring new variables of the structure type later in the program, declaring parameters of the structure type and, if the structure is being used like a C++ class, specifying the name of the constructor and destructor.
11
2006 Pearson Education, Inc. All rights reserved.
22.2 Structure Definitions (Cont.)
• Structures (Cont.)– Built-in operations that may be performed on structure
objects• Assignment operator =• Address operator &• Member-access operators . and ->
• sizeof operator
• Other operators can be overloaded to work with any structure
12
2006 Pearson Education, Inc. All rights reserved.
22.2 Structure Definitions (Cont.)
• Structures (Cont.)– “Holes” in a structure
• Because some computers store data types only on certain memory boundaries
• Structure members are not necessarily stored in consecutive memory
13
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.2
Comparing structures is a compilation error.
14
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.1 | Possible storage alignment for a variable of type Example, showing an undefined area in memory.
15
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.1
Because the size of data items of a particular type is machine dependent, and because storage alignment considerations are machine dependent, so too is the representation of a structure.
16
2006 Pearson Education, Inc. All rights reserved.
22.3 Initializing Structures
• Initializing a structure– Structures can be initialized using initializer lists
• Example
– Card oneCard = { "Three", "Hearts" };• Initializes member face to "Three"• Initializes member suit to "Hearts"
• If there are fewer initializers than members
– Remaining members are initialized to default values
– Structure variables declared outside any function are initialized to default values
– Structure variables may also be initialized by• Assigning a structure variable of the same type
• Assigning to individual members
17
2006 Pearson Education, Inc. All rights reserved.
22.4 Using Structures with Functions
• Passing structures to functions– Entire structure or individual members can be passed to
functions
– Structures are passed by value, by default• To pass a structure by reference
– Pass address of the structure object
– Pass reference to the structure object
– Pass array of the structure objects
– To pass an array by value• Encapsulate it inside a structure, which is passed by value
18
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 22.1
Passing structures (and especially large structures) by reference is more efficient than passing them by value (which requires the entire structure to be copied).
19
2006 Pearson Education, Inc. All rights reserved.
22.5 typedef
• Keyword typedef– Used for creating synonyms for previously defined data
types• Often defined to create shorter, simpler or more readable
type names
– Example• typedef Card *CardPtr;
– Defines type name CardPtr as a synonym for Card *
– Does not create a new type• Only a new type name that can be used as an alias for an
existing type name
20
2006 Pearson Education, Inc. All rights reserved.
Good Programming Practice 22.1
Capitalize typedef names to emphasize that these names are synonyms for other type names.
21
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.2
Synonyms for built-in data types can be created with typedef to make programs more portable. For example, a program can use typedef to create alias Integer for four-byte integers. Integer can then be aliased to int on systems with four-byte integers and can be aliased to long int on systems with two-byte integers where long int values occupy four bytes. Then, the programmer simply declares all four-byte integer variables to be of type Integer.
22
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.2: DeckOfCards.h
2 // Definition of class DeckOfCards that
3 // represents a deck of playing cards.
4
5 // Card structure definition
6 struct Card
7 {
8 char *face;
9 char *suit;
10 }; // end structure Card
11
12 // DeckOfCards class definition
13 class DeckOfCards
14 {
15 public:
16 DeckOfCards(); // constructor initializes deck
17 void shuffle(); // shuffles cards in deck
18 void deal(); // deals cards in deck
19
20 private:
21 Card deck[ 52 ]; // represents deck of cards
22 }; // end class DeckOfCards
Outline
DeckOfCards.h
(1 of 1)Define structure Card
Class DeckOfCards contains an array of Card structure objects
23
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.3: DeckOfCards.cpp
2 // Member-function definitions for class DeckOfCards that simulates
3 // the shuffling and dealing of a deck of playing cards.
4 #include <iostream>
5 using std::cout;
6 using std::left;
7 using std::right;
8
9 #include <iomanip>
10 using std::setw;
11
12 #include <cstdlib> // prototypes for rand and srand
13 using std::rand;
14 using std::srand;
15
16 #include <ctime> // prototype for time
17 using std::time;
18
19 #include "DeckOfCards.h" // DeckOfCards class definition
Outline
DeckOfCards.cpp
(1 of 3)
24
2006 Pearson Education, Inc. All rights reserved.
20
21 // no-argument DeckOfCards constructor intializes deck
22 DeckOfCards::DeckOfCards()
23 {
24 // initialize suit array
25 static char *suit[ 4 ] =
26 { "Hearts", "Diamonds", "Clubs", "Spades" };
27
28 // initialize face array
29 static char *face[ 13 ] =
30 { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven",
31 "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
32
33 // set values for deck of 52 Cards
34 for ( int i = 0; i < 52; i++ )
35 {
36 deck[ i ].face = face[ i % 13 ];
37 deck[ i ].suit = suit[ i / 13 ];
38 } // end for
39
40 srand( time( 0 ) ); // seed random number generator
41 } // end no-argument DeckOfCards constructor
Outline
DeckOfCards.cpp
(2 of 3)
Initialize Card members by assignment
25
2006 Pearson Education, Inc. All rights reserved.
42
43 // shuffle cards in deck
44 void DeckOfCards::shuffle()
45 {
46 // shuffle cards randomly
47 for ( int i = 0; i < 52; i++ )
48 {
49 int j = rand() % 52;
50 Card temp = deck[ i ];
51 deck[ i ] = deck[ j ];
52 deck[ j ] = temp;
53 } // end for
54 } // end function shuffle
55
56 // deal cards in deck
57 void DeckOfCards::deal()
58 {
59 // display each card’s face and suit
60 for ( int i = 0; i < 52; i++ )
61 cout << right << setw( 5 ) << deck[ i ].face << " of "
62 << left << setw( 8 ) << deck[ i ].suit
63 << ( ( i + 1 ) % 2 ? '\t' : '\n' );
64 } // end function deal
Outline
DeckOfCards.cpp
(3 of 3)Shuffle cards by performing 52
swaps in a single pass of the array
26
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.4: fig22_04.cpp
2 // Card shuffling and dealing program.
3 #include "DeckOfCards.h" // DeckOfCards class definition
4
5 int main()
6 {
7 DeckOfCards deckOfCards; // create DeckOfCards object
8
9 deckOfCards.shuffle(); // shuffle the cards in the deck
10 deckOfCards.deal(); // deal the cards in the deck
11 return 0; // indicates successful termination
12 } // end main
Outline
fig22_04.cpp
(1 of 2)
27
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_04.cpp
(2 of 2)
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
28
2006 Pearson Education, Inc. All rights reserved.
22.7 Bitwise Operators
• Bitwise manipulations– Used to manipulate the bits of integral operands
• Usually unsigned integers
• Bitwise operators– Bitwise AND (&)
• Sets each bit in result to 1 if corresponding bit in both operands is 1
– Bitwise inclusive OR (|)• Sets each bit in result to 1 if corresponding bit in either (or
both) operand(s) is 1
– Bitwise exclusive OR (^)• Sets each bit in result to 1 if corresponding bit in either
operand–but not both–is 1
29
2006 Pearson Education, Inc. All rights reserved.
22.7 Bitwise Operators (Cont.)
• Bitwise operators (Cont.)– Left shift (<<)
• Shifts bits of left operand to the left by number of bits specified in right operand
– Bits vacated to the right are replaced with 0s
– 1s shifted off the left are lost
– Right shift (>>)• Shifts bits in left operand to the right by number of bits
specified in right operand
– Bits vacated to the left
• Replaced with 0s for an unsigned integer
• Machine-dependent for a signed integer
– 1s shifted off the right are lost
30
2006 Pearson Education, Inc. All rights reserved.
22.7 Bitwise Operators (Cont.)
• Bitwise operators (Cont.)– Bitwise complement (~)
• Sets all 0 bits in operand to 1 in result and sets all 1 bits in operand to 0 in result
– Bitwise assignment operators• Bitwise AND assignment operator &=• Bitwise inclusive-OR assignment operator |=• Bitwise exclusive-OR assignment operator ^=• Left-shift assignment operator <<=• Right-shift with sign extension assignment operator >>=• (no bitwise complement assignment operator)
31
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.3
Bitwise data manipulations are machine dependent.
32
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.5 | Bitwise operators.
Operator Name Description
& bitwise AND The bits in the result are set to 1 if the corresponding bits in the two operands are both 1.
| bitwise inclusive OR The bits in the result are set to 1 if one or both of the corresponding bits in the two operands is 1.
bitwise exclusive OR The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1.
<< left shift Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from right with 0 bits.
>> right shift with sign extension
Shifts the bits of the first operand right by the -number of bits specified by the second operand; the method of filling from the left is machine -dependent.
~ bitwise complement All 0 bits are set to 1 and all 1 bits are set to 0.
33
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.6: fig22_06.cpp
2 // Printing an unsigned integer in bits.
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl;
7
8 #include <iomanip>
9 using std::setw;
10
11 void displayBits( unsigned ); // prototype
12
13 int main()
14 {
15 unsigned inputValue; // integral value to print in binary
16
17 cout << "Enter an unsigned integer: ";
18 cin >> inputValue;
19 displayBits( inputValue );
20 return 0;
21 } // end main
Outline
fig22_06.cpp
(1 of 2)
34
2006 Pearson Education, Inc. All rights reserved.
22
23 // display bits of an unsigned integer value
24 void displayBits( unsigned value )
25 {
26 const int SHIFT = 8 * sizeof( unsigned ) - 1;
27 const unsigned MASK = 1 << SHIFT;
28
29 cout << setw( 10 ) << value << " = ";
30
31 // display bits
32 for ( unsigned i = 1; i <= SHIFT + 1; i++ )
33 {
34 cout << ( value & MASK ? '1' : '0' );
35 value <<= 1; // shift value left by 1
36
37 if ( i % 8 == 0 ) // output a space after 8 bits
38 cout << ' ';
39 } // end for
40
41 cout << endl; 42 } // end function displayBits Enter an unsigned integer: 65000 65000 = 00000000 00000000 11111101 11101000 Enter an unsigned integer: 29 29 = 00000000 00000000 00000000 00011101
Outline
fig22_06.cpp
(2 of 2)
The value of constant SHIFT is 1 less than the total number of bits required to store an unsigned object
Assign constant MASK the value 1 << SHIFT, which has a 1 in the leftmost bit and 0s filled to the right
Determine whether a 1 or a 0 should be printed for the current leftmost bit of variable value
Shift variable value left by 1 bit so we can display the next bit over
35
2006 Pearson Education, Inc. All rights reserved.
22.7 Bitwise Operators (Cont.)
• Mask operand– An integer value with specific bits set to 1
– Used to hide some bits in a value while selecting other bits
– Examples• 00000000 11101000 (value)10000000 00000000 (MASK)----------------- perform bitwise AND operation00000000 00000000 (value & MASK)
• 11101000 00000000 (value)10000000 00000000 (MASK)----------------- perform bitwise AND operation10000000 00000000 (value & MASK)
36
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.3
Using the logical AND operator (&&) for the bitwise AND operator (&) and vice versa is a logic error.
37
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.7 | Results of combining two bits with the bitwise AND operator (&).
Bit 1 Bit 2 Bit 1 & Bit 2
0 0 0
1 0 0
0 1 0
1 1 1
38
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.8: fig22_08.cpp
2 // Using the bitwise AND, bitwise inclusive OR, bitwise
3 // exclusive OR and bitwise complement operators.
4 #include <iostream>
5 using std::cout;
6
7 #include <iomanip>
8 using std::endl;
9 using std::setw;
10
11 void displayBits( unsigned ); // prototype
12
13 int main()
14 {
15 unsigned number1;
16 unsigned number2;
17 unsigned mask;
18 unsigned setBits;
19
20 // demonstrate bitwise &
21 number1 = 2179876355;
22 mask = 1;
23 cout << "The result of combining the following\n";
24 displayBits( number1 );
25 displayBits( mask );
26 cout << "using the bitwise AND operator & is\n";
27 displayBits( number1 & mask );
Outline
fig22_08.cpp
(1 of 4)
Assign 10000001 11101110 01000110 00000011 to number1
Assign 00000000 00000000 00000000 00000001 to mask
All the bits except the low-order bit in variable number1 are “masked off” (hidden) by “ANDing” with constant MASK
39
2006 Pearson Education, Inc. All rights reserved.
28
29 // demonstrate bitwise |
30 number1 = 15;
31 setBits = 241;
32 cout << "\nThe result of combining the following\n";
33 displayBits( number1 );
34 displayBits( setBits );
35 cout << "using the bitwise inclusive OR operator | is\n";
36 displayBits( number1 | setBits );
37
38 // demonstrate bitwise exclusive OR
39 number1 = 139;
40 number2 = 199;
41 cout << "\nThe result of combining the following\n";
42 displayBits( number1 );
43 displayBits( number2 );
44 cout << "using the bitwise exclusive OR operator ^ is\n";
45 displayBits( number1 ^ number2 );
46
47 // demonstrate bitwise complement
48 number1 = 21845;
49 cout << "\nThe one's complement of\n";
50 displayBits( number1 );
51 cout << "is" << endl;
52 displayBits( ~number1 );
53 return 0;
54 } // end main
Outline
fig22_08.cpp
(2 of 4)Combine number1 and setBits using
the bitwise OR operator in the expression number1 | setBits
Combine number1 and number2 with the exclusive-OR operator in the expression number1 ^ number2
“Take the one’s complement” of variable number1 with expression ~number1
40
2006 Pearson Education, Inc. All rights reserved.
55
56 // display bits of an unsigned integer value
57 void displayBits( unsigned value )
58 {
59 const int SHIFT = 8 * sizeof( unsigned ) - 1;
60 const unsigned MASK = 1 << SHIFT;
61
62 cout << setw( 10 ) << value << " = ";
63
64 // display bits
65 for ( unsigned i = 1; i <= SHIFT + 1; i++ )
66 {
67 cout << ( value & MASK ? '1' : '0' );
68 value <<= 1; // shift value left by 1
69
70 if ( i % 8 == 0 ) // output a space after 8 bits
71 cout << ' ';
72 } // end for
73
74 cout << endl;
75 } // end function displayBits
Outline
fig22_08.cpp
(3 of 4)
41
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_08.cpp
(4 of 4)
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
42
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.4
Using the logical OR operator (||) for the bitwise OR operator (|) and vice versa is a logic error.
43
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.9 | Combining two bits with the bitwise inclusive-OR operator (|).
Bit 1 Bit 2 Bit 1 | Bit 2
0 0 0
1 0 1
0 1 1
1 1 1
44
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.10 | Combining two bits with the bitwise exclusive-OR operator (^).
Bit 1 Bit 2 Bit 1 ^ Bit 2
0 0 0
1 0 1
0 1 1
1 1 0
45
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.11: fig22_11.cpp
2 // Using the bitwise shift operators.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 void displayBits( unsigned ); // prototype
11
12 int main()
13 {
14 unsigned number1 = 960;
15
16 // demonstrate bitwise left shift
17 cout << "The result of left shifting\n";
18 displayBits( number1 );
19 cout << "8 bit positions using the left-shift operator is\n";
20 displayBits( number1 << 8 );
21
22 // demonstrate bitwise right shift
23 cout << "\nThe result of right shifting\n";
24 displayBits( number1 );
25 cout << "8 bit positions using the right-shift operator is\n";
26 displayBits( number1 >> 8 );
27 return 0;
28 } // end main
Outline
fig22_11.cpp
(1 of 3)
Left-shift variable number1 by 8 bits
Right-shift variable number1 by 8 bits
46
2006 Pearson Education, Inc. All rights reserved.
29
30 // display bits of an unsigned integer value
31 void displayBits( unsigned value )
32 {
33 const int SHIFT = 8 * sizeof( unsigned ) - 1;
34 const unsigned MASK = 1 << SHIFT;
35
36 cout << setw( 10 ) << value << " = ";
37
38 // display bits
39 for ( unsigned i = 1; i <= SHIFT + 1; i++ )
40 {
41 cout << ( value & MASK ? '1' : '0' );
42 value <<= 1; // shift value left by 1
43
44 if ( i % 8 == 0 ) // output a space after 8 bits
45 cout << ' ';
46 } // end for
47
48 cout << endl;
49 } // end function displayBits
Outline
fig22_11.cpp
(2 of 3)
47
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_11.cpp
(3 of 3)
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
48
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.5
The result of shifting a value is undefined if the right operand is negative or if the right operand is greater than or equal to the number of bits in which the left operand is stored.
49
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.4
The result of right-shifting a signed value is machine dependent. Some machines fill with zeros and others use the sign bit.
50
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.12 | Bitwise assignment operators.
Bitwise assignment operators
&= Bitwise AND assignment operator.
|= Bitwise inclusive-OR assignment operator.
^= Bitwise exclusive-OR assignment operator.
<<= Left-shift assignment operator.
>>= Right-shift with sign extension assignment operator.
51
2006 Pearson Education, Inc. All rights reserved.
22.8 Bit Fields
• Bit Fields– Members for which programmer specifies exact number of
bits to use to store its value• Enable better memory utilization by storing data in minimal
space
• Must be integral type or enum type member of a class or structure
• Specified width (in bits) of a bit field must be an integer constant
52
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 22.2
Bit fields help conserve storage.
53
2006 Pearson Education, Inc. All rights reserved.
22.8 Bit Fields (Cont.)
• Bit Fields (Cont.)– Example
• struct BitCard{ unsigned face : 4; unsigned suit : 2; unsigned color : 1;};
– unsigned variable face is stored in 4 bits
– unsigned variable suit is stored in 2 bits
– unsigned variable color is stored in 1 bit
54
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.13 | Operator precedence and associativity.
Operators Associativity Type
:: (unary; right to left) :: (binary; left to right) left to right highest
() [] . -> ++ -- static_cast< type >() left to right unary
++ -- + - ! delete sizeof right to left unary
* ~ & new * / % left to right multiplicative
+ - left to right additive
<< >> left to right shifting
< <= > >= left to right relational
== != left to right equality
& left to right bitwise AND
^ left to right bitwise XOR
| left to right bitwise OR
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= &= |= ^= <<= >>= right to left assignment
, left to right comma
55
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.14: DeckOfCards.h
2 // Definition of class DeckOfCards that
3 // represents a deck of playing cards.
4
5 // BitCard structure definition with bit fields
6 struct BitCard
7 {
8 unsigned face : 4; // 4 bits; 0-15
9 unsigned suit : 2; // 2 bits; 0-3
10 unsigned color : 1; // 1 bit; 0-1
11 }; // end struct BitCard
12
13 // DeckOfCards class definition
14 class DeckOfCards
15 {
16 public:
17 DeckOfCards(); // constructor initializes deck
18 void deal(); // deals cards in deck
19
20 private:
21 BitCard deck[ 52 ]; // represents deck of cards
22 }; // end class DeckOfCards
Outline
DeckOfCards.h
(1 of 1)
Declare bit fields face, suit and color
Create array deck containing 52 BitCard structure variables
56
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.15: DeckOfCards.cpp
2 // Member-function definitions for class DeckOfCards that simulates
3 // the shuffling and dealing of a deck of playing cards.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9 using std::setw;
10
11 #include "DeckOfCards.h" // DeckOfCards class definition
12
13 // no-argument DeckOfCards constructor intializes deck
14 DeckOfCards::DeckOfCards()
15 {
16 for ( int i = 0; i <= 51; i++ )
17 {
18 deck[ i ].face = i % 13; // faces in order
19 deck[ i ].suit = i / 13; // suits in order
20 deck[ i ].color = i / 26; // colors in order
21 } // end for
22 } // end no-argument DeckOfCards constructor
Outline
DeckOfCards.cpp
(1 of 2)
Insert the 52 cards in the deck array
57
2006 Pearson Education, Inc. All rights reserved.
23
24 // deal cards in deck
25 void DeckOfCards::deal()
26 {
27 for ( int k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ )
28 cout << "Card:" << setw( 3 ) << deck[ k1 ].face
29 << " Suit:" << setw( 2 ) << deck[ k1 ].suit
30 << " Color:" << setw( 2 ) << deck[ k1 ].color
31 << " " << "Card:" << setw( 3 ) << deck[ k2 ].face
32 << " Suit:" << setw( 2 ) << deck[ k2 ].suit
33 << " Color:" << setw( 2 ) << deck[ k2 ].color << endl;
34 } // end function deal
Outline
DeckOfCards.cpp
(2 of 2)
Print the 52 cards, accessing the bit fields exactly as any other member
58
2006 Pearson Education, Inc. All rights reserved.
22.8 Bit Fields (Cont.)
• Bit Fields (Cont.)– Unnamed bit fields
• Are used as padding
• Example
– unsigned a : 13;unsigned : 3;unsigned b : 4;
• Nothing can be stored in unnamed 3-bit field
• Member b is stored in another storage unit
59
2006 Pearson Education, Inc. All rights reserved.
22.8 Bit Fields (Cont.)
• Bit Fields (Cont.)– Unnamed bit fields with zero width
• Align next bit field on new storage-unit boundary
• Example
– unsigned a : 13;unsigned : 0;unsigned b : 4;
• Skips remaining bits in a’s storage unit
• Member b is aligned on next storage-unit boundary
60
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.16: fig22_16.cpp
2 // Card shuffling and dealing program.
3 #include "DeckOfCards.h" // DeckOfCards class definition
4
5 int main()
6 {
7 DeckOfCards deckOfCards; // create DeckOfCards object
8 deckOfCards.deal(); // deal the cards in the deck
9 return 0; // indicates successful termination
10 } // end main
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
Outline
fig22_16.cpp
(1 of 1)
61
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.5
Bit-field manipulations are machine dependent. For example, some computers allow bit fields to cross word boundaries, whereas others do not.
62
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.6
Attempting to access individual bits of a bit field with subscripting as if they were elements of an array is a compilation error. Bit fields are not “arrays of bits.”
63
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.7
Attempting to take the address of a bit field (the & operator may not be used with bit fields because a pointer can designate only a particular byte in memory and bit fields can start in the middle of a byte) is a compilation error.
64
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 22.3
Although bit fields save space, using them can cause the compiler to generate slower-executing machine-language code. This occurs because it takes extra machine-language operations to access only portions of an addressable storage unit. This is one of many examples of the space-time trade-offs that occur in computer science.
65
2006 Pearson Education, Inc. All rights reserved.
22.9 Character-Handling Library
• Character-handling library functions– Perform useful tests and manipulations of character data
– Manipulates characters as ints• char cannot store EOF (usually -1)
• All functions take an int argument and return an int
– Included in <cctype> header file
66
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.17 | Character-handling library functions. (Part 1 of 2)
Prototype Description
int isdigit( int c ) Returns true if c is a digit and false otherwise.
int isalpha( int c ) Returns true if c is a letter and false otherwise.
int isalnum( int c ) Returns true if c is a digit or a letter and false otherwise.
int isxdigit( int c ) Returns true if c is a hexadecimal digit character and false otherwise. (See Appendix D, Number Systems, for a detailed explanation of binary, octal, decimal and hexadecimal numbers.)
int islower( int c ) Returns true if c is a lowercase letter and false otherwise.
int isupper( int c ) Returns true if c is an uppercase letter; false otherwise.
int tolower( int c ) If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower returns the argument unchanged.
int toupper( int c ) If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper returns the argument unchanged.
67
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.17 | Character-handling library functions. (Part 2 of 2)
Prototype Description
int isspace( int c ) Returns true if c is a white-space character—newline ('\n'), space (' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and false otherwise.
int iscntrl( int c ) Returns true if c is a control character, such as newline ('\n'), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t'), vertical tab ('\v'), alert ('\a'), or backspace ('\b')—and false otherwise.
int ispunct( int c ) Returns true if c is a printing character other than a space, a digit, or a letter and false otherwise.
int isprint( int c ) Returns true value if c is a printing character including space (' ') and false otherwise.
int isgraph( int c ) Returns true if c is a printing character other than space (' ') and false otherwise.
68
2006 Pearson Education, Inc. All rights reserved.
22.9 Character-Handling Library (Cont.)
• Character-handling library functions (Cont.)– Function isdigit
• Returns true if argument is a digit (0-9)
– Function isalpha• Returns true if argument is an uppercase or lowercase
letter (A-Z, a-z)
– Function isalnum• Returns true if argument is an uppercase letter, lowercase
letter or digit (A-Z, a-z, 0-9)
– Function isxdigit• Returns true if argument is a hexadecimal digit (A-F, a-f, 0-9)
69
2006 Pearson Education, Inc. All rights reserved.
22.9 Character-Handling Library (Cont.)
• Character-handling library functions (Cont.)– Function islower
• Returns true if argument is a lowercase letter (a-z)
– Function isupper• Returns true if argument is an uppercase letter (A-Z)
– Function tolower• Returns its uppercase-letter argument as a lowercase letter
• Returns its argument unchanged if it is not an uppercase letter
– Function toupper• Returns its lowercase-letter argument as an uppercase letter
• Returns its argument unchanged if it is not a lowercase letter
70
2006 Pearson Education, Inc. All rights reserved.
22.9 Character-Handling Library (Cont.)
• Character-handling library functions (Cont.)– Function isspace
• Returns true if argument is a white-space character
– Such as space (' '), form feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), vertical tab ('\v')
– Function iscntrl• Returns true if argument is a control character
– Such as horizontal tab ('\t'), vertical tab ('\v'), form feed ('\f'), alert ('\a'), backspace ('\b'), carriage return ('\r'), newline ('\n')
71
2006 Pearson Education, Inc. All rights reserved.
22.9 Character-Handling Library (Cont.)
• Character-handling library functions (Cont.)– Function ispunct
• Returns true if argument is a printing character other than a space, digit or letter
– Such as $, #, (, ), [, ], {, }, ;, : or %
– Function isprint• Returns true if argument is a displayable character
(including the space character)
– Function isgraph• Returns true if argument is a graphical, displayable
character (not including the space character)
72
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.18: fig22_18.cpp
2 // Using functions isdigit, isalpha, isalnum and isxdigit.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cctype> // character-handling function prototypes
8 using std::isalnum;
9 using std::isalpha;
10 using std::isdigit;
11 using std::isxdigit;
12
13 int main()
14 {
15 cout << "According to isdigit:\n"
16 << ( isdigit( '8' ) ? "8 is a" : "8 is not a" ) << " digit\n"
17 << ( isdigit( '#' ) ? "# is a" : "# is not a" ) << " digit\n";
18
19 cout << "\nAccording to isalpha:\n"
20 << ( isalpha( 'A' ) ? "A is a" : "A is not a" ) << " letter\n"
21 << ( isalpha( 'b' ) ? "b is a" : "b is not a" ) << " letter\n"
22 << ( isalpha( '&' ) ? "& is a" : "& is not a" ) << " letter\n"
23 << ( isalpha( '4' ) ? "4 is a" : "4 is not a" ) << " letter\n";
Outline
fig22_18.cpp
(1 of 3)
Use the conditional operator (?:) with the return value of each function to determine the correct string to print
73
2006 Pearson Education, Inc. All rights reserved.
24
25 cout << "\nAccording to isalnum:\n"
26 << ( isalnum( 'A' ) ? "A is a" : "A is not a" )
27 << " digit or a letter\n"
28 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" )
29 << " digit or a letter\n"
30 << ( isalnum( '#' ) ? "# is a" : "# is not a" )
31 << " digit or a letter\n";
32
33 cout << "\nAccording to isxdigit:\n"
34 << ( isxdigit( 'F' ) ? "F is a" : "F is not a" )
35 << " hexadecimal digit\n"
36 << ( isxdigit( 'J' ) ? "J is a" : "J is not a" )
37 << " hexadecimal digit\n"
38 << ( isxdigit( '7' ) ? "7 is a" : "7 is not a" )
39 << " hexadecimal digit\n"
40 << ( isxdigit( '$' ) ? "$ is a" : "$ is not a" )
41 << " hexadecimal digit\n"
42 << ( isxdigit( 'f' ) ? "f is a" : "f is not a" )
43 << " hexadecimal digit" << endl;
44 return 0;
45 } // end main
Outline
fig22_18.cpp
(2 of 3)
74
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_18.cpp
(3 of 3)
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
75
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.19: fig22_19.cpp
2 // Using functions islower, isupper, tolower and toupper.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cctype> // character-handling function prototypes
8 using std::islower;
9 using std::isupper;
10 using std::tolower;
11 using std::toupper;
12
13 int main()
14 {
15 cout << "According to islower:\n"
16 << ( islower( 'p' ) ? "p is a" : "p is not a" )
17 << " lowercase letter\n"
18 << ( islower( 'P' ) ? "P is a" : "P is not a" )
19 << " lowercase letter\n"
20 << ( islower( '5' ) ? "5 is a" : "5 is not a" )
21 << " lowercase letter\n"
22 << ( islower( '!' ) ? "! is a" : "! is not a" )
23 << " lowercase letter\n";
Outline
fig22_19.cpp
(1 of 3)
76
2006 Pearson Education, Inc. All rights reserved.
24
25 cout << "\nAccording to isupper:\n"
26 << ( isupper( 'D' ) ? "D is an" : "D is not an" )
27 << " uppercase letter\n"
28 << ( isupper( 'd' ) ? "d is an" : "d is not an" )
29 << " uppercase letter\n"
30 << ( isupper( '8' ) ? "8 is an" : "8 is not an" )
31 << " uppercase letter\n"
32 << ( isupper( '$' ) ? "$ is an" : "$ is not an" )
33 << " uppercase letter\n";
34
35 cout << "\nu converted to uppercase is "
36 << static_cast< char >( toupper( 'u' ) )
37 << "\n7 converted to uppercase is "
38 << static_cast< char >( toupper( '7' ) )
39 << "\n$ converted to uppercase is "
40 << static_cast< char >( toupper( '$' ) )
41 << "\nL converted to lowercase is "
42 << static_cast< char >( tolower( 'L' ) ) << endl;
43 return 0;
44 } // end main
Outline
fig22_19.cpp
(2 of 3)
77
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_19.cpp
(3 of 3)
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
78
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.20: fig22_20.cpp
2 // Using functions isspace, iscntrl, ispunct, isprint, isgraph.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cctype> // character-handling function prototypes
8 using std::iscntrl;
9 using std::isgraph;
10 using std::isprint;
11 using std::ispunct;
12 using std::isspace;
13
14 int main()
15 {
16 cout << "According to isspace:\nNewline "
17 << ( isspace( '\n' ) ? "is a" : "is not a" )
18 << " whitespace character\nHorizontal tab "
19 << ( isspace( '\t' ) ? "is a" : "is not a" )
20 << " whitespace character\n"
21 << ( isspace( '%' ) ? "% is a" : "% is not a" )
22 << " whitespace character\n";
23
24 cout << "\nAccording to iscntrl:\nNewline "
25 << ( iscntrl( '\n' ) ? "is a" : "is not a" )
26 << " control character\n"
27 << ( iscntrl( '$' ) ? "$ is a" : "$ is not a" )
28 << " control character\n";
Outline
fig22_20.cpp
(1 of 3)
79
2006 Pearson Education, Inc. All rights reserved.
29
30 cout << "\nAccording to ispunct:\n"
31 << ( ispunct( ';' ) ? "; is a" : "; is not a" )
32 << " punctuation character\n"
33 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )
34 << " punctuation character\n"
35 << ( ispunct( '#' ) ? "# is a" : "# is not a" )
36 << " punctuation character\n";
37
38 cout << "\nAccording to isprint:\n"
39 << ( isprint( '$' ) ? "$ is a" : "$ is not a" )
40 << " printing character\nAlert "
41 << ( isprint( '\a' ) ? "is a" : "is not a" )
42 << " printing character\nSpace "
43 << ( isprint( ' ' ) ? "is a" : "is not a" ) 44 << " printing character\n";
45
46 cout << "\nAccording to isgraph:\n"
47 << ( isgraph( 'Q' ) ? "Q is a" : "Q is not a" )
48 << " printing character other than a space\nSpace "
49 << ( isgraph( ' ' ) ? "is a" : "is not a" )
50 << " printing character other than a space" << endl;
51 return 0;
52 } // end main
Outline
fig22_20.cpp
(2 of 3)
80
2006 Pearson Education, Inc. All rights reserved.
Outline
fig22_20.cpp
(3 of 3)
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 Space is 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
81
2006 Pearson Education, Inc. All rights reserved.
22.10 Pointer-Based String-Conversion Functions
• Pointer-based string-conversion functions– Convert pointer-based strings of characters to integer and
floating-point values• Return 0 if their string arguments cannot be converted
– Included in general-utilities library <cstdlib>
82
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.21 | Pointer-based string-conversion functions of the general-utilities library. (Part 1 of 2)
Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double. If the string cannot be converted, 0 is returned.
int atoi( const char *nPtr ) Converts the string nPtr to int. If the string cannot be converted, 0 is returned.
long atol( const char *nPtr ) Converts the string nPtr to long int. If the string cannot be converted, 0 is returned.
double strtod( const char *nPtr, char **endPtr )
Converts the string nPtr to double. endPtr is the address of a pointer to the rest of the string after the double. If the string cannot be converted, 0 is returned.
83
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.21 | Pointer-based string-conversion functions of the general-utilities library. (Part 2 of 2)
Prototype Description
long strtol( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to long. endPtr is the address of a pointer to the rest of the string after the long. If the string cannot be converted, 0 is returned. The base parameter indicates the base of the number to convert (e.g., 8 for octal, 10 for decimal or 16 for hexadecimal). The default is decimal.
unsigned long strtoul( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to unsigned long. endPtr is the address of a pointer to the rest of the string after the unsigned long. If the string cannot be converted, 0 is returned. The base parameter indicates the base of the number to convert (e.g., 8 for octal, 10 for decimal or 16 for hexadecimal). The default is decimal.
84
2006 Pearson Education, Inc. All rights reserved.
22.10 Pointer-Based String-Conversion Functions (Cont.)
• Pointer-based string-conversion functions (Cont.)– Function atof
• Converts string argument to a double value
– Function atoi• Converts string argument to an int value
– Function atol• Converts string argument to a long value
– Function strtod• Converts a sequence of characters to a double value
• Second argument specifies a char ** pointer
– Sets the char * at that address to point to the location of the first character after the converted portion
85
2006 Pearson Education, Inc. All rights reserved.
22.10 Pointer-Based String-Conversion Functions (Cont.)
• Pointer-based string-conversion functions (Cont.)– Function strtol
• Converts a sequence of characters to a long value
• Second argument specifies a char ** pointer
– Sets the char * at that address to point to the location of the first character after the converted portion
• Third argument specifies the value’s base
– 0 specifies octal, decimal or hexadecimal, depending on the initial character(s) – 0 for octal, 0x for hexadecimal and 1-9 for decimal
– 2-36 specify that value for the base
• For bases 11-36, characters A-Z represent values 10 to 35
86
2006 Pearson Education, Inc. All rights reserved.
22.10 Pointer-Based String-Conversion Functions (Cont.)
• Pointer-based string-conversion functions (Cont.)– Function strtoul
• Converts a sequence of characters to an unsigned long value
• Second argument specifies a char ** pointer
– Sets the char * at that address to point to the location of the first character after the converted portion
• Third argument specifies the value’s base
– 0 specifies octal, decimal or hexadecimal, depending on the initial character(s) – 0 for octal, 0x for hexadecimal and 1-9 for decimal
– 2-36 specify that value for the base
• For bases 11-36, characters A-Z represent values 10 to 35
87
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.22: fig22_22.cpp
2 // Using atof.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // atof prototype
8 using std::atof;
9
10 int main()
11 {
12 double d = atof( "99.0" ); // convert string to double
13
14 cout << "The string \"99.0\" converted to double is " << d
15 << "\nThe converted value divided by 2 is " << d / 2.0 << endl;
16 return 0;
17 } // end main The string "99.0" converted to double is 99 The converted value divided by 2 is 49.5
Outline
fig22_22.cpp
(1 of 1)Convert a string that represents a floating-
point number to a double value
88
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.23: Fig22_23.cpp
2 // Using atoi.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // atoi prototype
8 using std::atoi;
9
10 int main()
11 {
12 int i = atoi( "2593" ); // convert string to int
13
14 cout << "The string \"2593\" converted to int is " << i
15 << "\nThe converted value minus 593 is " << i - 593 << endl;
16 return 0;
17 } // end main The string "2593" converted to int is 2593 The converted value minus 593 is 2000
Outline
Fig22_23.cpp
(1 of 1)Convert a string of digits that represents
an integer to an int value
89
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.24: fig22_24.cpp
2 // Using atol.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // atol prototype
8 using std::atol;
9
10 int main()
11 {
12 long x = atol( "1000000" ); // convert string to long
13
14 cout << "The string \"1000000\" converted to long is " << x
15 << "\nThe converted value divided by 2 is " << x / 2 << endl;
16 return 0;
17 } // end main The string "1000000" converted to long int is 1000000 The converted value divided by 2 is 500000
Outline
fig22_24.cpp
(1 of 1)Convert a string of digits representing
a long integer to a long value
90
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.25: fig22_25.cpp
2 // Using strtod.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // strtod prototype
8 using std::strtod;
9
10 int main()
11 {
12 double d;
13 const char *string1 = "51.2% are admitted";
14 char *stringPtr;
15
16 d = strtod( string1, &stringPtr ); // convert characters to double
17
18 cout << "The string \"" << string1
19 << "\" is converted to the\ndouble value " << d
20 << " and the string \"" << stringPtr << "\"" << endl;
21 return 0;
22 } // end main The string "51.2% are admitted" is converted to the double value 51.2 and the string "% are admitted"
Outline
fig22_25.cpp
(1 of 1)
Convert a double value from the beginning of string1
Display the remainder of the string after the converted portion
91
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.26: fig22_26.cpp
2 // Using strtol.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // strtol prototype
8 using std::strtol;
9
10 int main()
11 {
12 long x;
13 const char *string1 = "-1234567abc";
14 char *remainderPtr;
15
16 x = strtol( string1, &remainderPtr, 0 ); // convert characters to long
17
18 cout << "The original string is \"" << string1
19 << "\"\nThe converted value is " << x
20 << "\nThe remainder of the original string is \"" << remainderPtr
21 << "\"\nThe converted value plus 567 is " << x + 567 << endl;
22 return 0;
23 } // end main 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
Outline
fig22_26.cpp
(1 of 1)
Convert a sequence of characters representing an integer to a long value
Third argument 0 indicates decimal base because the initial character is '1'
Display remainder of the string after the converted portion
92
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.27: fig22_27.cpp
2 // Using strtoul.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstdlib> // strtoul prototype
8 using std::strtoul;
9
10 int main()
11 {
12 unsigned long x;
13 const char *string1 = "1234567abc";
14 char *remainderPtr;
15
16 // convert a sequence of characters to unsigned long
17 x = strtoul( string1, &remainderPtr, 0 );
18
19 cout << "The original string is \"" << string1
20 << "\"\nThe converted value is " << x
21 << "\nThe remainder of the original string is \"" << remainderPtr
22 << "\"\nThe converted value minus 567 is " << x - 567 << endl;
23 return 0;
24 } // end main
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
Outline
fig22_27.cpp
(1 of 1)
Convert a sequence of characters representing an unsigned long integer to an unsigned long value
Indicate that the value to be converted can be in octal, decimal or hexadecimal format, depending on the initial characters
Display the remainder of the string after the converted portion
93
2006 Pearson Education, Inc. All rights reserved.
22.11 Search Functions of the Pointer-Based String-Handling Library
• Pointer-based string search functions– Used to search strings for characters and other strings
– size_t• Defined as the integral type of the value returned by operator sizeof
94
2006 Pearson Education, Inc. All rights reserved.
Portability Tip 22.6
Type size_t is a system-dependent synonym for either type unsigned long or type unsigned int.
95
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.28 | Search functions of the pointer-based string-handling library.
Prototype Description
char *strchr( const char *s, int c )
Locates the first occurrence of character c in string s. If c is found, a pointer to c in s is returned. Otherwise, a null pointer is returned.
char *strrchr( const char *s, int c )
Searches from the end of string s and locates the last occurrence of character c in string s. If c is found, a pointer to c in string s is returned. Otherwise, a null pointer is returned.
size_t strspn( const char *s1, const char *s2 )
Determines and returns the length of the initial segment of string s1 consisting only of characters contained in string s2.
char *strpbrk( const char *s1, const char *s2 )
Locates the first occurrence in string s1 of any character in string s2. If a character from string s2 is found, a pointer to the character in string s1 is returned. Otherwise, a null pointer is returned.
size_t strcspn( const char *s1, const char *s2 )
Determines and returns the length of the initial segment of string s1 consisting of characters not contained in string s2.
char *strstr( const char *s1, const char *s2 )
Locates the first occurrence in string s1 of string s2. If the string is found, a pointer to the string in s1 is returned. Otherwise, a null pointer is returned.
96
2006 Pearson Education, Inc. All rights reserved.
22.11 Search Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string search functions (Cont.)– Function strchr
• Searches for the first occurrence of a character in a string
– Returns pointer to the character if it is found
– Otherwise, returns null pointer
– Function strcspn• Returns length of the initial part of the first string argument
that does not contain any character from the second string argument
97
2006 Pearson Education, Inc. All rights reserved.
22.11 Search Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string search functions (Cont.)– Function strpbrk
• Searches for the first occurrence in the first string argument of any character in the second string argument
– Returns pointer to the character if one is found
– Otherwise, returns null pointer
– Function strrchr• Searches for the last occurrence of a character in a string
– Returns pointer to the character if one is found
– Otherwise, returns null pointer
98
2006 Pearson Education, Inc. All rights reserved.
22.11 Search Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string search functions (Cont.)– Function strspn
• Returns length of the initial part of the first string argument that contains only characters from the second string argument
– Function strstr• Searches for the first occurrence of the second string
argument in the first string argument
– Returns pointer to the substring if one is found
– Otherwise, returns null pointer
99
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.29: fig22_29.cpp
2 // Using strchr.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strchr prototype
8 using std::strchr;
9
10 int main()
11 {
12 const char *string1 = "This is a test";
13 char character1 = 'a';
14 char character2 = 'z';
15
16 // search for character1 in string1
17 if ( strchr( string1, character1 ) != NULL )
18 cout << '\'' << character1 << "' was found in \""
19 << string1 << "\".\n";
20 else
21 cout << '\'' << character1 << "' was not found in \""
22 << string1 << "\".\n";
Outline
fig22_29.cpp
(1 of 2)
Search for the first occurrence of 'a' in the string "This is a test"
100
2006 Pearson Education, Inc. All rights reserved.
23
24 // search for character2 in string1
25 if ( strchr( string1, character2 ) != NULL )
26 cout << '\'' << character2 << "' was found in \""
27 << string1 << "\".\n";
28 else
29 cout << '\'' << character2 << "' was not found in \""
30 << string1 << "\"." << endl;
31
32 return 0;
33 } // end main 'a' was found in "This is a test". 'z' was not found in "This is a test".
Outline
fig22_29.cpp
(2 of 2)
Search for the first occurrence of 'z' in the string "This is a test"
101
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.30: fig22_30.cpp
2 // Using strcspn.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strcspn prototype
8 using std::strcspn;
9
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 return 0;
20 } // end main string1 = The value is 3.14159 string2 = 1234567890 The length of the initial segment of string1 containing no characters from string2 = 13
Outline
fig22_30.cpp
(1 of 1)
Determine the length of the initial part of "The value is 3.14159" that does not contain any characters from "1234567890"
102
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.31: fig22_31.cpp
2 // Using strpbrk.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strpbrk prototype
8 using std::strpbrk;
9
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 ) << "\' is the first character "
17 << "to appear in\n\"" << string1 << '\"' << endl;
18 return 0;
19 } // end main Of the characters in "beware" 'a' is the first character to appear in "This is a test"
Outline
fig22_31.cpp
(1 of 1)
Search for the first occurrence in "This is a test" of any character in "beware"
103
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.32: fig22_32.cpp
2 // Using strrchr.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strrchr prototype
8 using std::strrchr;
9
10 int main()
11 {
12 const char *string1 = "A zoo has many animals including zebras";
13 char c = 'z';
14
15 cout << "string1 = " << string1 << "\n" << endl;
16 cout << "The remainder of string1 beginning with the\n"
17 << "last occurrence of character '"
18 << c << "' is: \"" << strrchr( string1, c ) << '\"' << endl;
19 return 0;
20 } // end main string1 = A zoo has many animals including zebras The remainder of string1 beginning with the last occurrence of character 'z' is: "zebras"
Outline
fig22_32.cpp
(1 of 1)
Search for the last occurrence of 'z' in "A zoo has many animals including zebras"
104
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.33: fig22_33.cpp
2 // Using strspn.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strspn prototype
8 using std::strspn;
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 << "\nstring2 = " << string2
16 << "\n\nThe length of the initial segment of string1\n"
17 << "containing only characters from string2 = "
18 << strspn( string1, string2 ) << endl;
19 return 0;
20 } // end main string1 = The value is 3.14159 string2 = aehils Tuv The length of the initial segment of string1 containing only characters from string2 = 13
Outline
fig22_33.cpp
(1 of 1)
Determine the length of the initial part of "The value is 3.14159" that contains only characters from "aehils Tuv"
105
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.34: fig22_34.cpp
2 // Using strstr.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strstr prototype
8 using std::strstr;
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 return 0;
20 } // end main string1 = abcdefabcdef string2 = def The remainder of string1 beginning with the first occurrence of string2 is: defabcdef
Outline
fig22_34.cpp
(1 of 1)
Search for the first occurrence of "def" in "abcdefabcdef"
106
2006 Pearson Education, Inc. All rights reserved.
22.12 Memory Functions of the Pointer-Based String-Handling Library
• Pointer-based string memory functions– Facilitate manipulating, comparing and searching blocks
of memory• Treat blocks of memory as arrays of bytes
– Referred to as “objects”
• Can manipulate any block of data
– Use arguments of type void *• Any pointer can be converted to type void *
107
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.35 | Memory functions of the string-handling library.
Prototype Description
void *memcpy( void *s1, const void *s2, size_t n )
Copies n characters from the object pointed to by s2 into the object pointed to by s1. A pointer to the resulting object is returned. The area from which characters are copied is not allowed to overlap the area to which characters are copied.
void *memmove( void *s1, const void *s2, size_t n )
Copies n characters from the object pointed to by s2 into the object pointed to by s1. The copy is performed as if the characters were first copied from the object pointed to by s2 into a temporary array, and then copied from the temporary array into the object pointed to by s1. A pointer to the resulting object is returned. The area from which characters are copied is allowed to overlap the area to which characters are copied.
int memcmp( const void *s1, const void *s2, size_t n )
Compares the first n characters of the objects pointed to by s1 and s2. The function returns 0, less than 0, or greater than 0 if s1 is equal to, less than or greater than s2, respectively.
void *memchr( const void *s, int c, size_t n )
Locates the first occurrence of c (converted to unsigned char) in the first n characters of the object pointed to by s. If c is found, a pointer to c in the object is returned. Otherwise, 0 is returned.
void *memset( void *s, int c, size_t n )
Copies c (converted to unsigned char) into the first n characters of the object pointed to by s. A pointer to the result is returned.
108
2006 Pearson Education, Inc. All rights reserved.
22.12 Memory Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string memory functions (Cont.)– Function memcpy
• Copies specified number of bytes from the second object into the first object
• Undefined if the two objects overlap in memory
– Function memmove• Copies specified number of bytes from the second object into
the first object
– Performed as if the bytes were first copied to temporary storage
• Can be used even if the two objects overlap in memory
109
2006 Pearson Education, Inc. All rights reserved.
22.12 Memory Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string memory functions (Cont.)– Function memcmp
• Compares specified number of bytes in the first object with the corresponding bytes in the second object
– Returns positive value if first object is greater
– Returns zero if both objects are equal
– Returns negative value if first object is less
– Function memchr• Searches for the first occurrence of the specified byte
(unsigned char) in the specified number of bytes of an object
– Returns pointer to the byte if one is found
– Otherwise, returns null pointer
110
2006 Pearson Education, Inc. All rights reserved.
22.12 Memory Functions of the Pointer-Based String-Handling Library (Cont.)
• Pointer-based string memory functions (Cont.)– Function memset
• Copies specified byte value into the specified number of bytes of an object
111
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.36: fig22_36.cpp
2 // Using memcpy.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // memcpy prototype
8 using std::memcpy;
9
10 int main()
11 {
12 char s1[ 17 ];
13
14 // 17 total characters (includes terminating null)
15 char s2[] = "Copy this string";
16
17 memcpy( s1, s2, 17 ); // copy 17 characters from s2 to s1
18
19 cout << "After s2 is copied into s1 with memcpy,\n"
20 << "s1 contains \"" << s1 << '\"' << endl;
21 return 0;
22 } // end main After s2 is copied into s1 with memcpy, s1 contains "Copy this string"
Outline
fig22_36.cpp
(1 of 1)
Copy the string in array s2 to array s1
112
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 22.8
String-manipulation functions other than memmove that copy characters have undefined results when copying takes place between parts of the same string.
113
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.37: fig22_37.cpp
2 // Using memmove.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // memmove prototype
8 using std::memmove;
9
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 ) ) << endl;
17 return 0;
18 } // end main The string in array x before memmove is: Home Sweet Home The string in array x after memmove is: Sweet Home Home
Outline
fig22_37.cpp
(1 of 1)
Copy the last 10 bytes of array x into the first 10 bytes of array x
114
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.38: fig22_38.cpp
2 // Using memcmp.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 #include <cstring> // memcmp prototype
11 using std::memcmp;
12
13 int main()
14 {
15 char s1[] = "ABCDEFG";
16 char s2[] = "ABCDXYZ";
17
18 cout << "s1 = " << s1 << "\ns2 = " << s2 << endl
19 << "\nmemcmp(s1, s2, 4) = " << setw( 3 ) << memcmp( s1, s2, 4 )
20 << "\nmemcmp(s1, s2, 7) = " << setw( 3 ) << memcmp( s1, s2, 7 )
21 << "\nmemcmp(s2, s1, 7) = " << setw( 3 ) << memcmp( s2, s1, 7 )
22 << endl;
23 return 0;
24 } // end main s1 = ABCDEFG s2 = ABCDXYZ memcmp(s1, s2, 4) = 0 memcmp(s1, s2, 7) = -1 memcmp(s2, s1, 7) = 1
Outline
fig22_38.cpp
(1 of 1)
Compare bytes in s1 with bytes in s2
115
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.39: fig22_39.cpp
2 // Using memchr.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // memchr prototype
8 using std::memchr;
9
10 int main()
11 {
12 char s[] = "This is a string";
13
14 cout << "s = " << s << "\n" << endl;
15 cout << "The remainder of s after character 'r' is found is \""
16 << static_cast< char * >( memchr( s, 'r', 16 ) ) << '\"' << endl;
17 return 0;
18 } // end main s = This is a string The remainder of s after character 'r' is found is "ring"
Outline
fig22_39.cpp
(1 of 1)
Search for 'r' in "ring"
116
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 22.40: fig22_40.cpp
2 // Using memset.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // memset prototype
8 using std::memset;
9
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 ) ) << endl;
17 return 0;
18 } // end main string1 = BBBBBBBBBBBBBB string1 after memset = bbbbbbbBBBBBBB
Outline
fig22_40.cpp
(1 of 1)
Copy 'b' into the first 7 bytes of string1