Chapter 18 - Bits, Characters, Strings and Structures. Outline 18.1 Introduction 18.2 Structure Definitions 18.3 Initializing Structures 18.4 Using Structures with Functions 18.5 typedef 18.6 Example: High-Performance Card-Shuffling and Dealing Simulation - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
2003 Prentice Hall, Inc. All rights reserved.
1Chapter 18 - Bits, Characters, Strings and Structures
Outline18.1 Introduction18.2 Structure Definitions18.3 Initializing Structures18.4 Using Structures with Functions18.5 typedef18.6 Example: High-Performance Card-Shuffling and Dealing Simulation18.7 Bitwise Operators18.8 Bit Fields18.9 Character-Handling Library18.10 String-Conversion Functions18.11 Search Functions of the String-Handling Library18.12 Memory Functions of the String-Handling Library
2003 Prentice Hall, Inc. All rights reserved.
2
18.1 Introduction
• Structures, bits, characters, C-style strings– C-like techniques– Useful for C++ programmers working with legacy C code
• Structures– Hold variables of different data types– Similar to classes, but all data members public– Examine how to use structures
• Make card shuffling simulation
2003 Prentice Hall, Inc. All rights reserved.
3
18.2 Structure Definitions
• Structure definitionstruct Card {
char *face; char *suit; };
– Keyword struct– Card is structure name
• Used to declare variable of structure type– Data/functions declared within braces
• Structure members need unique names• Structure cannot contain instance of itself, only a pointer
– Definition does not reserve memory– Definition ends with semicolon
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
47 // place strings into Card structures48 void fillDeck( Card * const wDeck, 49 char *wFace[], char *wSuit[] )50 {51 for ( int i = 0; i < 52; i++ ) {52 wDeck[ i ].face = wFace[ i % 13 ];53 wDeck[ i ].suit = wSuit[ i / 13 ];54 55 } // end for56 57 } // end function fillDeck58 59 // shuffle cards60 void shuffle( Card * const wDeck )61 {62 for ( int i = 0; i < 52; i++ ) {63 int j = rand() % 52;64 Card temp = wDeck[ i ]; 65 wDeck[ i ] = wDeck[ j ];66 wDeck[ j ] = temp; 67 68 } // end for69 70 } // end function shuffle71
Create every face and suit. Note format for accessing a data member in an array of structs.
Pick a random card in deck (0-51) and swap with current card. Notice the use of structure assignment.
2003 Prentice Hall, Inc.All rights reserved.
Outline14
fig18_02.cpp(4 of 4)
72 // deal cards73 void deal( Card * const wDeck )74 {75 for ( int i = 0; i < 52; i++ )76 cout << right << setw( 5 ) << wDeck[ i ].face << " of " 77 << left << setw( 8 ) << wDeck[ i ].suit 78 << ( ( i + 1 ) % 2 ? '\t' : '\n' );79 80 } // end function deal
2003 Prentice Hall, Inc.All rights reserved.
Outline15
fig18_02.cppoutput (1 of 1)
King of Clubs Ten of Diamonds Five of Diamonds Jack of ClubsSeven of Spades Five of ClubsThree of Spades King of Hearts Ten of Clubs Eight of SpadesEight of Hearts Six of Hearts Nine of Diamonds Nine of ClubsThree of Diamonds Queen of Hearts Six of Clubs Seven of HeartsSeven of Diamonds Jack of Diamonds Jack of Spades King of DiamondsDeuce of Diamonds Four of ClubsThree of Clubs Five of HeartsEight of Clubs Ace of HeartsDeuce of Spades Ace of Clubs Ten of Spades Eight of Diamonds Ten of Hearts Six of SpadesQueen of Diamonds Nine of HeartsSeven of Clubs Queen of ClubsDeuce of Clubs Queen of SpadesThree of Hearts Five of SpadesDeuce of Hearts Jack of Hearts Four of Hearts Ace of Diamonds Nine of Spades Four of Diamonds Ace of Spades Six of Diamonds Four of Spades King of Spades
2003 Prentice Hall, Inc. All rights reserved.
16
18.7 Bitwise Operators
• Data represented internally as sequences of bits– Each bit can be 0 or 1– 8 bits form a byte
• char is one byte• Other data types larger (int, long, etc.)
– Low-level software requires bit and byte manipulation• Operating systems, networking
2003 Prentice Hall, Inc. All rights reserved.
17
18.7 Bitwise Operators
• Bit operators– Many are overloaded– & (bitwise AND)
• 1 if both bits 1, 0 otherwise– | (bitwise inclusive OR)
• 1 if either bit 1, 0 otherwise– ^ (bitwise exclusive OR)
• 1 if exactly one bit is 1, 0 otherwise• Alternatively: 1 if the bits are different
– ~ (bitwise one's complement)• Flips 0 bits to 1, and vice versa
2003 Prentice Hall, Inc. All rights reserved.
18
18.7 Bitwise Operators
• Bit operators– << (left shift)
• Moves all bits left by specified amount• Fills from right with 0• 1 << SHIFTAMOUNT
– >> (right shift with sign extension)• Moves bits right by specified amount• Fill from left can vary
2003 Prentice Hall, Inc. All rights reserved.
19
18.7 Bitwise Operators
• Next program– Print values in their binary representation– Example: unsigned integer 3
• 00000000 00000000 00000000 00000011• (For a machine with 4-byte integers)• Computer stores number in this form
• Using masks– Integer value with specific bits set to 1– Used to hide some bits while selecting others
• Use with AND
2003 Prentice Hall, Inc. All rights reserved.
20
18.7 Bitwise Operators
• Mask example– Suppose we want to see leftmost bit of a number– AND with mask
Bitwise AND value and mask. If it is nonzero (true), then the leftmost digit is a 1.Shift value left by 1 to
examine next bit. Note use of <<= (same as value = value << 1).
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.
Outline25
fig18_07.cpp(1 of 4)
1 // Fig. 18.7: fig18_07.cpp2 // Using the bitwise AND, bitwise inclusive OR, bitwise3 // exclusive OR and bitwise complement operators.4 #include <iostream>5 6 using std::cout;7 using std::cin;8 9 #include <iomanip>10 11 using std::endl;12 using std::setw;13 14 void displayBits( unsigned ); // prototype15 16 int main()17 {18 unsigned number1;19 unsigned number2;20 unsigned mask;21 unsigned setBits;22
2003 Prentice Hall, Inc.All rights reserved.
Outline26
fig18_07.cpp(2 of 4)
23 // demonstrate bitwise &24 number1 = 2179876355;25 mask = 1;26 cout << "The result of combining the following\n";27 displayBits( number1 );28 displayBits( mask );29 cout << "using the bitwise AND operator & is\n";30 displayBits( number1 & mask );31 32 // demonstrate bitwise |33 number1 = 15;34 setBits = 241;35 cout << "\nThe result of combining the following\n";36 displayBits( number1 );37 displayBits( setBits );38 cout << "using the bitwise inclusive OR operator | is\n";39 displayBits( number1 | setBits );40 41 // demonstrate bitwise exclusive OR42 number1 = 139;43 number2 = 199;44 cout << "\nThe result of combining the following\n";45 displayBits( number1 );46 displayBits( number2 );47 cout << "using the bitwise exclusive OR operator ^ is\n";48 displayBits( number1 ^ number2 );
2003 Prentice Hall, Inc.All rights reserved.
Outline27
fig18_07.cpp(3 of 4)
49 50 // demonstrate bitwise complement51 number1 = 21845;52 cout << "\nThe one's complement of\n";53 displayBits( number1 );54 cout << "is" << endl;55 displayBits( ~number1 );56 57 return 0;58 59 } // end main60 61 // display bits of an unsigned integer value62 void displayBits( unsigned value )63 {64 const int SHIFT = 8 * sizeof( unsigned ) - 1;65 const unsigned MASK = 1 << SHIFT;66 67 cout << setw( 10 ) << value << " = ";68 69 for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {70 cout << ( value & MASK ? '1' : '0' );71 value <<= 1; // shift value left by 172 73 if ( i % 8 == 0 ) // output a space after 8 bits74 cout << ' ';75 76 } // end for
2003 Prentice Hall, Inc.All rights reserved.
Outline28
fig18_07.cpp(4 of 4)
fig18_07.cppoutput (1 of 1)
77 78 cout << endl;79 80 } // end function displayBits
The result of combining the following2179876355 = 10000001 11101110 01000110 00000011 1 = 00000000 00000000 00000000 00000001using 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 11110001using 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 11000111using the bitwise exclusive OR operator ^ is 76 = 00000000 00000000 00000000 01001100 The one's complement of 21845 = 00000000 00000000 01010101 01010101is4294945450 = 11111111 11111111 10101010 10101010
2003 Prentice Hall, Inc.All rights reserved.
Outline29
fig18_07.cpp(1 of 3)
1 // Fig. 18.11: fig18_11.cpp2 // Using the bitwise shift operators.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 #include <iomanip>10 11 using std::setw;12 13 void displayBits( unsigned ); // prototype14 15 int main()16 {17 unsigned number1 = 960;18 19 // demonstrate bitwise left shift20 cout << "The result of left shifting\n";21 displayBits( number1 );22 cout << "8 bit positions using the left "23 << "shift operator is\n";24 displayBits( number1 << 8 );25
2003 Prentice Hall, Inc.All rights reserved.
Outline30
fig18_07.cpp(2 of 3)
26 // demonstrate bitwise right shift27 cout << "\nThe result of right shifting\n";28 displayBits( number1 );29 cout << "8 bit positions using the right "30 << "shift operator is\n";31 displayBits( number1 >> 8 );32 33 return 0;34 35 } // end main36 37 // display bits of an unsigned integer value38 void displayBits( unsigned value )39 {40 const int SHIFT = 8 * sizeof( unsigned ) - 1;41 const unsigned MASK = 1 << SHIFT;42 43 cout << setw( 10 ) << value << " = ";44 45 for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {46 cout << ( value & MASK ? '1' : '0' );47 value <<= 1; // shift value left by 148 49 if ( i % 8 == 0 ) // output a space after 8 bits50 cout << ' ';51 52 } // end for
2003 Prentice Hall, Inc.All rights reserved.
Outline31
fig18_07.cpp(3 of 3)
fig18_07.cppoutput (1 of 1)
53 54 cout << endl;55 56 } // end function displayBits
The result of left shifting 960 = 00000000 00000000 00000011 110000008 bit positions using the left shift operator is 245760 = 00000000 00000011 11000000 00000000 The result of right shifting 960 = 00000000 00000000 00000011 110000008 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.
Outline34
fig18_14.cpp(1 of 3)
1 // Fig. 18.14: fig18_14.cpp2 // Representing cards with bit fields in a struct.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 // BitCard structure definition with bit fields13 struct BitCard { 14 unsigned face : 4; // 4 bits; 0-15 15 unsigned suit : 2; // 2 bits; 0-3 16 unsigned color : 1; // 1 bit; 0-1 17 18 }; // end struct BitBard 19 20 void fillDeck( BitCard * const ); // prototype21 void deal( const BitCard * const ); // prototype22 23 int main()24 {25 BitCard deck[ 52 ];26 27 fillDeck( deck );28 deal( deck );
Declare bit fields inside a structure to store card data.
2003 Prentice Hall, Inc.All rights reserved.
Outline35
fig18_14.cpp(2 of 3)
29 30 return 0;31 32 } // end main33 34 // initialize BitCards35 void fillDeck( BitCard * const wDeck )36 {37 for ( int i = 0; i <= 51; i++ ) {38 wDeck[ i ].face = i % 13; 39 wDeck[ i ].suit = i / 13; 40 wDeck[ i ].color = i / 26;41 42 } // end for43 44 } // end function fillDeck45
Assign to bit fields as normal, but be careful of each field's range.
• Other notes– Bit fields are not arrays of bits (cannot use [])– Cannot take address of bit fields– Use unnamed bit fields to pad structure
Struct Example {unsigned a : 13;unsigned : 3;unsigned b : 4;
};– Use unnamed, zero-width fields to align to boundary
Struct Example {unsigned a : 13;unsigned : 0;unsigned b : 4;
};• Automatically aligns b to next boundary
2003 Prentice Hall, Inc. All rights reserved.
39
18.9 Character-Handling Library
• Character Handling Library– <cctype>– Functions to perform tests and manipulations on characters– Pass character as argument
• Character represented by an int– char does not allow negative values
• Characters often manipulated as ints• EOF usually has value -1
2003 Prentice Hall, Inc. All rights reserved.
40
18.9 Character-Handling Library
• Upcoming example– isalpha( int c )
• (All character functions take int argument)• Returns true if c is a letter (A-Z, a-z)• Returns false otherwise
– isdigit• Returns true if digit (0-9)
– isalnum• Returns true if letter or digit (A-Z, a-z, 0-9)
– isxdigit• Returns true if hexadecimal digit (A-F, a-f, 0-9)
2003 Prentice Hall, Inc.All rights reserved.
Outline41
fig18_17.cpp(1 of 2)
1 // Fig. 18.17: fig18_17.cpp2 // Using functions isdigit, isalpha, isalnum and isxdigit.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to isdigit:\n"13 << ( isdigit( '8' ) ? "8 is a" : "8 is not a" ) 14 << " digit\n"15 << ( isdigit( '#' ) ? "# is a" : "# is not a" ) 16 << " digit\n";17 18 cout << "\nAccording to isalpha:\n"19 << ( isalpha( 'A' ) ? "A is a" : "A is not a" ) 20 << " letter\n"21 << ( isalpha( 'b' ) ? "b is a" : "b is not a" ) 22 << " letter\n"23 << ( isalpha( '&' ) ? "& is a" : "& is not a" ) 24 << " letter\n"25 << ( isalpha( '4' ) ? "4 is a" : "4 is not a" ) 26 << " letter\n";27
Note use of conditional operator:
condition ? value if true : value if false
2003 Prentice Hall, Inc.All rights reserved.
Outline42
fig18_17.cpp(2 of 2)
28 cout << "\nAccording to isalnum:\n"29 << ( isalnum( 'A' ) ? "A is a" : "A is not a" )30 << " digit or a letter\n"31 << ( isalnum( '8' ) ? "8 is a" : "8 is not a" )32 << " digit or a letter\n"33 << ( isalnum( '#' ) ? "# is a" : "# is not a" )34 << " digit or a letter\n";35 36 cout << "\nAccording to isxdigit:\n"37 << ( isxdigit( 'F' ) ? "F is a" : "F is not a" )38 << " hexadecimal digit\n"39 << ( isxdigit( 'J' ) ? "J is a" : "J is not a" )40 << " hexadecimal digit\n"41 << ( isxdigit( '7' ) ? "7 is a" : "7 is not a" )42 << " hexadecimal digit\n"43 << ( isxdigit( '$' ) ? "$ is a" : "$ is not a" )44 << " hexadecimal digit\n"45 << ( isxdigit( 'f' ) ? "f is a" : "f is not a" )46 << " hexadecimal digit" << endl;47 48 return 0;49 50 } // end main
2003 Prentice Hall, Inc.All rights reserved.
Outline43
fig18_17.cppoutput (1 of 1)
According to isdigit:8 is a digit# is not a digit According to isalpha:A is a letterb is a letter& is not a letter4 is not a letter According to isalnum:A is a digit or a letter8 is a digit or a letter# is not a digit or a letter
According to isxdigit:F is a hexadecimal digitJ is not a hexadecimal digit7 is a hexadecimal digit$ is not a hexadecimal digitf 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.
Outline45
fig18_18.cpp(1 of 2)
1 // Fig. 18.18: fig18_18.cpp2 // Using functions islower, isupper, tolower and toupper.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to islower:\n"13 << ( islower( 'p' ) ? "p is a" : "p is not a" ) 14 << " lowercase letter\n"15 << ( islower( 'P' ) ? "P is a" : "P is not a" ) 16 << " lowercase letter\n"17 << ( islower( '5' ) ? "5 is a" : "5 is not a" ) 18 << " lowercase letter\n"19 << ( islower( '!' ) ? "! is a" : "! is not a" ) 20 << " lowercase letter\n";21 22 cout << "\nAccording to isupper:\n"23 << ( isupper( 'D' ) ? "D is an" : "D is not an" ) 24 << " uppercase letter\n"25 << ( isupper( 'd' ) ? "d is an" : "d is not an" ) 26 << " uppercase letter\n"27 << ( isupper( '8' ) ? "8 is an" : "8 is not an" ) 28 << " uppercase letter\n"
2003 Prentice Hall, Inc.All rights reserved.
Outline46
fig18_18.cpp(2 of 2)
29 << ( isupper( '$' ) ? "$ is an" : "$ is not an" ) 30 << " uppercase letter\n";31 32 cout << "\nu converted to uppercase is " 33 << static_cast< char >( toupper( 'u' ) )34 << "\n7 converted to uppercase is " 35 << static_cast< char >( toupper( '7' ) )36 << "\n$ converted to uppercase is " 37 << static_cast< char >( toupper( '$' ) )38 << "\nL converted to lowercase is " 39 << static_cast< char >( tolower( 'L' ) ) << endl;40 41 return 0;42 43 } // end main
2003 Prentice Hall, Inc.All rights reserved.
Outline47
fig18_18.cppoutput (1 of 1)
According to islower:p is a lowercase letterP is not a lowercase letter5 is not a lowercase letter! is not a lowercase letter According to isupper:D is an uppercase letterd is not an uppercase letter8 is not an uppercase letter$ is not an uppercase letter u converted to uppercase is U7 converted to uppercase is 7$ converted to uppercase is $L converted to lowercase is l
2003 Prentice Hall, Inc. All rights reserved.
48
18.9 Character-Handling Library
• Upcoming example– isspace
• Returns true if space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v'
– iscntrl• Returns true if control character, such as tabs, form feed,
• 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.
Outline50
fig18_19.cpp(1 of 2)
1 // Fig. 18.19: fig18_19.cpp2 // Using functions isspace, iscntrl, ispunct, isprint, isgraph.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cctype> // character-handling function prototypes9 10 int main()11 {12 cout << "According to isspace:\nNewline " 13 << ( isspace( '\n' ) ? "is a" : "is not a" )14 << " whitespace character\nHorizontal tab " 15 << ( isspace( '\t' ) ? "is a" : "is not a" )16 << " whitespace character\n"17 << ( isspace( '%' ) ? "% is a" : "% is not a" )18 << " whitespace character\n";19 20 cout << "\nAccording to iscntrl:\nNewline " 21 << ( iscntrl( '\n' ) ? "is a" : "is not a" )22 << " control character\n"23 << ( iscntrl( '$' ) ? "$ is a" : "$ is not a" )24 << " control character\n";25
2003 Prentice Hall, Inc.All rights reserved.
Outline51
fig18_19.cpp(2 of 2)
26 cout << "\nAccording to ispunct:\n"27 << ( ispunct( ';' ) ? "; is a" : "; is not a" )28 << " punctuation character\n"29 << ( ispunct( 'Y' ) ? "Y is a" : "Y is not a" )30 << " punctuation character\n"31 << ( ispunct( '#' ) ? "# is a" : "# is not a" )32 << " punctuation character\n";33 34 cout << "\nAccording to isprint:\n"35 << ( isprint( '$' ) ? "$ is a" : "$ is not a" )36 << " printing character\nAlert " 37 << ( isprint( '\a' ) ? "is a" : "is not a" )38 << " printing character\n";39 40 cout << "\nAccording to isgraph:\n"41 << ( isgraph( 'Q' ) ? "Q is a" : "Q is not a" )42 << " printing character other than a space\nSpace " 43 << ( isgraph( ' ' ) ? "is a" : "is not a" )44 << " printing character other than a space" << endl;45 46 return 0;47 48 } // end main
2003 Prentice Hall, Inc.All rights reserved.
Outline52
fig18_19.cppoutput (1 of 1)
According to isspace:Newline is a whitespace characterHorizontal 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 characterY is not a punctuation character# is a punctuation character According to isprint:$ is a printing characterAlert is not a printing character According to isgraph:Q is a printing character other than a spaceSpace 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.
Outline55
fig18_21.cpp(1 of 1)
fig18_21.cppoutput (1 of 1)
1 // Fig. 18.21: fig18_21.cpp2 // Using atof.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atof prototype9 10 int main()11 {12 double d = atof( "99.0" );13 14 cout << "The string \"99.0\" converted to double is "15 << d << "\nThe converted value divided by 2 is "16 << d / 2.0 << endl;17 18 return 0;19 20 } // end main
The string "99.0" converted to double is 99The converted value divided by 2 is 49.5
2003 Prentice Hall, Inc.All rights reserved.
Outline56
fig18_22.cpp(1 of 1)
fig18_22.cppoutput (1 of 1)
1 // Fig. 18.22: fig18_22.cpp2 // Using atoi.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atoi prototype9 10 int main()11 {12 int i = atoi( "2593" );13 14 cout << "The string \"2593\" converted to int is " << i15 << "\nThe converted value minus 593 is " << i - 593 16 << endl;17 18 return 0;19 20 } // end main
The string "2593" converted to int is 2593The converted value minus 593 is 2000
2003 Prentice Hall, Inc.All rights reserved.
Outline57
fig18_23.cpp(1 of 1)
fig18_23.cppoutput (1 of 1)
1 // Fig. 18.23: fig18_23.cpp2 // Using atol.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // atol prototype9 10 int main()11 {12 long x = atol( "1000000" );13 14 cout << "The string \"1000000\" converted to long is " << x15 << "\nThe converted value divided by 2 is " << x / 2 16 << endl;17 18 return 0;19 20 } // end main
The string "1000000" converted to long int is 1000000The converted value divided by 2 is 500000
• 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.
Outline59
fig18_24.cpp(1 of 1)
fig18_24.cppoutput (1 of 1)
1 // Fig. 18.24: fig18_24.cpp2 // Using strtod.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtod prototype9 10 int main()11 {12 double d;13 const char *string1 = "51.2% are admitted";14 char *stringPtr;15 16 d = strtod( string1, &stringPtr );17 18 cout << "The string \"" << string1 19 << "\" is converted to the\ndouble value " << d 20 << " and the string \"" << stringPtr << "\"" << endl;21 22 return 0;23 24 } // end main
The string "51.2% are admitted" is converted to thedouble 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.
Outline61
fig18_25.cpp(1 of 1)
1 // Fig. 18.25: fig18_25.cpp2 // Using strtol.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtol prototype9 10 int main()11 {12 long x;13 const char *string1 = "-1234567abc";14 char *remainderPtr;15 16 x = strtol( string1, &remainderPtr, 0 );17 18 cout << "The original string is \"" << string119 << "\"\nThe converted value is " << x20 << "\nThe remainder of the original string is \""21 << remainderPtr22 << "\"\nThe converted value plus 567 is " 23 << x + 567 << endl;24 25 return 0;26 27 } // end main
2003 Prentice Hall, Inc.All rights reserved.
Outline62
fig18_25.cppoutput (1 of 1)
The original string is "-1234567abc"The converted value is -1234567The remainder of the original string is "abc"The converted value plus 567 is -1234000
2003 Prentice Hall, Inc.All rights reserved.
Outline63
fig18_26.cpp(1 of 1)
1 // Fig. 18.26: fig18_26.cpp2 // Using strtoul.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstdlib> // strtoul prototype9 10 int main()11 {12 unsigned long x;13 const char *string1 = "1234567abc";14 char *remainderPtr;15 16 x = strtoul( string1, &remainderPtr, 0 );17 18 cout << "The original string is \"" << string119 << "\"\nThe converted value is " << x20 << "\nThe remainder of the original string is \""21 << remainderPtr22 << "\"\nThe converted value minus 567 is " 23 << x - 567 << endl;24 25 return 0;26 27 } // end main
2003 Prentice Hall, Inc.All rights reserved.
Outline64
fig18_26.cppoutput (1 of 1)
The original string is "1234567abc"The converted value is 1234567The remainder of the original string is "abc"The converted value minus 567 is 1234000
2003 Prentice Hall, Inc. All rights reserved.
65
18.11 Search Functions of the String-Handling Library
• String handling library– Search strings for characters, other strings– Type size_t
• Defined as integer of type returned by sizeof
2003 Prentice Hall, Inc. All rights reserved.
66
18.11 Search Functions of the String-Handling Library
• Functions– char *strchr( const char *s, int c )
• Returns pointer to first occurrence of c in s• Returns NULL if not found
2003 Prentice Hall, Inc.All rights reserved.
Outline67
fig18_28.cpp(1 of 2)
1 // Fig. 18.28: fig18_28.cpp2 // Using strchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strchr prototype9 10 int main()11 {12 const char *string1 = "This is a test";13 char character1 = 'a';14 char character2 = 'z';15 16 if ( strchr( string1, character1 ) != NULL )17 cout << '\'' << character1 << "' was found in \""18 << string1 << "\".\n";19 else20 cout << '\'' << character1 << "' was not found in \""21 << string1 << "\".\n";22 23 if ( strchr( string1, character2 ) != NULL )24 cout << '\'' << character2 << "' was found in \""25 << string1 << "\".\n";26 else27 cout << '\'' << character2 << "' was not found in \""28 << string1 << "\"." << endl;
2003 Prentice Hall, Inc.All rights reserved.
Outline68
fig18_28.cpp(2 of 2)
fig18_28.cppoutput (1 of 1)
29 30 return 0;31 32 } // end main
'a' was found in "This is a test".'z' was not found in "This is a test".
2003 Prentice Hall, Inc. All rights reserved.
69
18.11 Search Functions of the String-Handling Library
• 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.
Outline70
fig18_29.cpp(1 of 1)
fig18_29.cppoutput (1 of 1)
1 // Fig. 18.29: fig18_29.cpp2 // Using strcspn.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strcspn prototype9 10 int main()11 {12 const char *string1 = "The value is 3.14159";13 const char *string2 = "1234567890";14 15 cout << "string1 = " << string1 << "\nstring2 = " << string216 << "\n\nThe length of the initial segment of string1"17 << "\ncontaining no characters from string2 = "18 << strcspn( string1, string2 ) << endl;19 20 return 0;21 22 } // end main
string1 = The value is 3.14159string2 = 1234567890 The length of the initial segment of string1containing no characters from string2 = 13
2003 Prentice Hall, Inc.All rights reserved.
Outline71
fig18_30.cpp(1 of 1)
fig18_30.cppoutput (1 of 1)
1 // Fig. 18.30: fig18_30.cpp2 // Using strpbrk.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strpbrk prototype9 10 int main()11 {12 const char *string1 = "This is a test";13 const char *string2 = "beware";14 15 cout << "Of the characters in \"" << string2 << "\"\n'"16 << *strpbrk( string1, string2 ) << '\''17 << " is the first character to appear in\n\""18 << string1 << '\"' << endl;19 20 return 0;21 22 } // end main
Of the characters in "beware"'a' is the first character to appear in"This is a test"
2003 Prentice Hall, Inc.All rights reserved.
Outline72
fig18_31.cpp(1 of 1)
fig18_31.cppoutput (1 of 1)
1 // Fig. 18.31: fig18_31.cpp2 // Using strrchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // strrchr prototype9 10 int main()11 {12 const char *string1 = 13 "A zoo has many animals including zebras";14 int c = 'z';15 16 cout << "The remainder of string1 beginning with the\n"17 << "last occurrence of character '" 18 << static_cast< char >( c ) // print as char not int19 << "' is: \"" << strrchr( string1, c ) << '\"' << endl;20 21 return 0;22 23 } // end main
The remainder of string1 beginning with thelast occurrence of character 'z' is: "zebras"
2003 Prentice Hall, Inc. All rights reserved.
73
18.11 Search Functions of the String-Handling Library
18.12 Memory Functions of the String-Handling Library
• Functions– void *memchr(const void *s, int c, size_t n )
• Finds first occurrence of c in first n characters of s• Returns pointer to c or NULL
– void *memset( void *s, int c, size_t n )• Copies c into first n characters of s• Returns pointer to result
2003 Prentice Hall, Inc.All rights reserved.
Outline86
fig18_38.cpp(1 of 1)
fig18_38.cppoutput (1 of 1)
1 // Fig. 18.38: fig18_38.cpp2 // Using memchr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memchr prototype9 10 int main()11 {12 char s[] = "This is a string";13 14 cout << "The remainder of s after character 'r' "15 << "is found is \"" 16 << static_cast< char * >( memchr( s, 'r', 16 ) )17 << '\"' << endl;18 19 return 0;20 21 } // end main
The remainder of s after character 'r' is found is "ring"
2003 Prentice Hall, Inc.All rights reserved.
Outline87
fig18_39.cpp(1 of 1)
fig18_39.cppoutput (1 of 1)
1 // Fig. 18.39: fig18_39.cpp2 // Using memset.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <cstring> // memset prototype9 10 int main()11 {12 char string1[ 15 ] = "BBBBBBBBBBBBBB";13 14 cout << "string1 = " << string1 << endl;15 cout << "string1 after memset = "16 << static_cast< char * >( memset( string1, 'b', 7 ) )17 << endl;18 19 return 0;20 21 } // end main
string1 = BBBBBBBBBBBBBBstring1 after memset = bbbbbbbBBBBBBB