2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions 16.3Initializing Structures 16.4Using Structures with Functions 16.5typedef 16.6Example: High-Performance Card-shuffling and Dealing Simulation 16.7Bitwise Operators 16.8Bit Fields 16.9Character-handling Library 16.10String Conversion Functions 16.11Search Functions of the String-handling Library 16.12Memory Functions of the String-handling Library 16.13Another Function of the String-handling Library
2000 Deitel & Associates, Inc. All rights reserved Structure Definitions struct Card { char *face; char *suit; }; Keyword struct introduces the definition for structure Card Identifier Card is the structure name and is used to declare variables of the structure type Card contains two members of type char * - face and suit Data members of a structure can vary in type –cannot contain an instance of itself –may contain a member that is a pointer to the same structure type Structure definition does not reserve space in memory –creates a new data type that used to declare structure variables.
2000 Deitel & Associates, Inc. All rights reserved Structure Definitions (II) Declarations –Declared like other variables: Card oneCard, deck[ 52 ], *cPtr; –Declared using comma separated list of variable names after the definition: struct Card { char *face; char *suit; } oneCard, deck[ 52 ], *cPtr; Valid Operations –assigning a structure to a structure of the same type –taking the address ( & ) of a structure –accessing the members of a structure –using the sizeof operator to determine the size of a structure
2000 Deitel & Associates, Inc. All rights reserved Initializing Structures Initializer lists –Example: Card oneCard = { "Three", "Hearts" }; Assignment statements –Example: Card threeHearts = oneCard ; –Or: Card threeHearts; threeHearts.face = Three; threeHearts.suit = Hearts;
2000 Deitel & Associates, Inc. All rights reserved Using Structures With Functions Passing structures to functions –pass entire structure –or, pass individual members –Both pass call by value To pass structures call-by-reference –pass its address –pass reference to it To pass arrays call-by-value –create a structure with the array as a member –pass the structure
2000 Deitel & Associates, Inc. All rights reserved Typedef typedef –creates synonyms (aliases) for previously defined data types –Use typedef to create shorter type names. –Example: typedef Card *CardPtr; defines a new type name CardPtr as a synonym for type Card * –typedef does not create a new data type only creates an alias
2000 Deitel & Associates, Inc. All rights reserved Example: High-Performance Card- shuffling and Dealing Simulation Pseudocode: –Create an array of Card structures –Put cards in the deck –Shuffle the deck –Deal the cards
2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Load headers 1.1 Define struct 1.2 Function prototypes 1.3 Initialize deck[] and face[] 1// Fig. 16.2: fig16_02.cpp 2// Card shuffling and dealing program using structures 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8using std::ios; 9 10#include 11 12using std::setiosflags; 13using std::setw; 14 15#include 16#include 17 18struct Card { 19 char *face; 20 char *suit; 21}; 22 23void fillDeck( Card * const, char *[], char *[] ); 24void shuffle( Card * const ); 25void deal( Card * const ); 26 27int main() 28{ 29 Card deck[ 52 ]; 30 char *face[] = { "Ace", "Deuce", "Three", "Four", 31 "Five", "Six", "Seven", "Eight", 32 "Nine", "Ten", "Jack", "Queen", 33 "King" };
2000 Deitel & Associates, Inc. All rights reserved. Outline 1.4 Initialize suit[] 2. Randomize 2. fillDeck 2.1 shuffle 2.2 deal 3. Function definitions 34 char *suit[] = { "Hearts", "Diamonds", 35 "Clubs", "Spades" }; srand( time( 0 ) ); // randomize 38 fillDeck( deck, face, suit ); 39 shuffle( deck ); 40 deal( deck ); 41 return 0; 42} 43 44void fillDeck( Card * const wDeck, char *wFace[], 45 char *wSuit[] ) 46{ 47 for ( int i = 0; i < 52; i++ ) { 48 wDeck[ i ].face = wFace[ i % 13 ]; 49 wDeck[ i ].suit = wSuit[ i / 13 ]; 50 } 51} Put all 52 cards in the deck. face and suit determined by remainder (modulus).
2000 Deitel & Associates, Inc. All rights reserved. Outline 3. Function definitions 52 53void shuffle( Card * const wDeck ) 54{ 55 for ( int i = 0; i < 52; i++ ) { 56 int j = rand() % 52; 57 Card temp = wDeck[ i ]; 58 wDeck[ i ] = wDeck[ j ]; 59 wDeck[ j ] = temp; 60 } 61} 62 63void deal( Card * const wDeck ) 64{ 65 for ( int i = 0; i < 52; i++ ) 66 cout << setiosflags( ios::right ) 67 << setw( 5 ) << wDeck[ i ].face << " of " 68 << setiosflags( ios::left ) 69 << setw( 8 ) << wDeck[ i ].suit 70 << ( ( i + 1 ) % 2 ? '\t' : '\n' ); 71} Select random number between 0 and 51. Swap element i with that element. Cycle through array and print out data.
2000 Deitel & Associates, Inc. All rights reserved. Outline Program Output Eight of Diamonds Ace of Hearts Eight of Clubs Five of Spades Seven of Hearts Deuce of Diamonds Ace of Clubs Ten of Diamonds Deuce of Spades Six of Diamonds Seven of Spades Deuce of Clubs Jack of Clubs Ten of Spades King of Hearts Jack of Diamonds Three of Hearts Three of Diamonds Three of Clubs Nine of Clubs Ten of Hearts Deuce of Hearts Ten of Clubs Seven of Diamonds Six of Clubs Queen of Spades Six of Hearts Three of Spades Nine of Diamonds Ace of Diamonds Jack of Spades Five of Clubs King of Diamonds Seven of Clubs Nine of Spades Four of Hearts Six of Spades Eight of Spades Queen of Diamonds Five of Diamonds Ace of Spades Nine of Hearts King of Clubs Five of Hearts King of Spades Four of Diamonds Queen of Hearts Eight of Hearts Four of Spades Jack of Hearts Four of Clubs Queen of Clubs
2000 Deitel & Associates, Inc. All rights reserved Bitwise Operators All data represented internally as sequences of bits –Each bit can be either 0 or 1 –a sequence of 8 bits forms a byte OperatorNameDescription & bitwise AND The bits in the result are set to 1 if the corresponding bits in the two operands are both 1. | bitwise OR The bits in the result are set to 1 if at least one 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 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. ~ Ones complement All 0 bits are set to 1 and all 1 bits are set to 0.
2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Function definition 1.1 Initialize variable 2. Input variable 1// Fig. 16.5: fig16_05.cpp 2// Printing an unsigned integer in bits 3#include 4 5using std::cout; 6using std::cin; 7 8#include 9 10using std::setw; 11using std::endl; 12 13void displayBits( unsigned ); 14 15int main() 16{ 17 unsigned x; cout << "Enter an unsigned integer: "; 20 cin >> x;
2000 Deitel & Associates, Inc. All rights reserved. Outline 2.1 Function call 3. Function definition Program Output 21 displayBits( x ); 22 return 0; 23} 24 25void displayBits( unsigned value ) 26{ 27 const int SHIFT = 8 * sizeof( unsigned ) - 1; 28 const unsigned MASK = 1 << SHIFT; cout << setw( 7 ) << value << " = "; for ( unsigned c = 1; c <= SHIFT + 1; c++ ) { 33 cout << ( value & MASK ? '1' : '0' ); 34 value <<= 1; if ( c % 8 == 0 ) 37 cout << ' '; 38 } cout << endl; 41} Enter an unsigned integer: = MASK created with only one set bit i.e. ( ) The MASK is constantly AND ed with value. MASK only contains one bit, so if the AND returns true it means value must have that bit. value is then shifted to test the next bit.
2000 Deitel & Associates, Inc. All rights reserved Bit Fields bit field –member of a structure whose size (in bits) has been specified –enable better memory utilization –must be declared as int or unsigned –Example: Struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color : 1; }; declaring bit fields –follow unsigned or int member with a colon (:) and an integer constant representing the width of the field
2000 Deitel & Associates, Inc. All rights reserved Character Handling Library Most data entered as characters –letters, digits, special symbols Character Handling Library –functions to perform tests and manipulations on character data –functions receive a character as an argument character represented by an int characters often manipulated as int s EOF usually has value -1
2000 Deitel & Associates, Inc. All rights reserved Character Handling Library (II) In
2000 Deitel & Associates, Inc. All rights reserved String Conversion Functions Conversion functions –In (general utilities library) –convert strings of digits to integer and floating-point values
2000 Deitel & Associates, Inc. All rights reserved Search Functions of the String Handling Library Load Search strings for –characters –other strings size_t –returned by some search functions –defined by standard as integral type of the value returned by sizeof
2000 Deitel & Associates, Inc. All rights reserved Search Functions of the String Handling Library (II)
2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Load header 1.1 Initialize strings 2. Function call 3. Output results Program Output 1// Fig : fig16_31.cpp 2// Using strrchr 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10int main() 11{ 12 const char *string1 = "A zoo has many animals " 13 "including zebras"; 14 int c = 'z'; cout << "The remainder of string1 beginning with the\n" 17 << "last occurrence of character '" 18 ( c ) 19 << "' is: \"" << strrchr( string1, c ) << '\"' << endl; 20 return 0; 21} The remainder of string1 beginning with the last occurrence of character 'z' is: "zebras"
2000 Deitel & Associates, Inc. All rights reserved. Outline 1. Load header 1.1 Initialize strings 2. Function call 3. Output results Program Output 1// Fig : fig16_32.cpp 2// Using strspn 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10int main() 11{ 12 const char *string1 = "The value is "; 13 const char *string2 = "aehils Tuv"; cout << "string1 = " << string1 16 << "\nstring2 = " << string2 17 << "\n\nThe length of the initial segment of string1\n" 18 << "containing only characters from string2 = " 19 << strspn( string1, string2 ) << endl; 20 return 0; 21} string1 = The value is string2 = aehils Tuv The length of the initial segment of string1 containing only characters from string2 = 13
2000 Deitel & Associates, Inc. All rights reserved Memory Functions of the String- handling Library Memory Functions –In –manipulate, compare, and search blocks of memory –can manipulate any block of data treat blocks as character arrays
2000 Deitel & Associates, Inc. All rights reserved Memory Functions of the String- handling Library (II) "Object" refers to a block of data
2000 Deitel & Associates, Inc. All rights reserved Another Function of the String- handling Library strerror –In –takes an error number and creates a message string #include int main() { cout << strerror( 2 ) << endl; return 0; } No such file or directory