Date post: | 05-Apr-2018 |
Category: |
Documents |
Upload: | billykwan13 |
View: | 219 times |
Download: | 0 times |
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 1/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Chapter 9:
Pointers
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 2/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.1Getting the Address of a Variable
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 3/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Getting the Address of aVariable• Each variable in program is stored at a
unique address• Use address operator & to get address of
a variable:int num = -99;cout << # // prints address
// in hexadecimal
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 4/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.2Pointer Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 5/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointer Variables
• Pointer variable : Often just called apointer, it's a variable that holds anaddress
• Because a pointer variable holds theaddress of another piece of data, it "points"to the data
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 6/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Something Like Pointers: Arrays
• We have already worked with something similarto pointers, when we learned to pass arrays asarguments to functions.
• For example, suppose we use this statement topass the array numbers to the showValues function:
showValues(numbers, SIZE);
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 7/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Something Like Pointers : Arrays
The values parameter, in the showValues function, points to the numbers array.
C++ automatically storesthe address of numbers inthe values parameter .
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 8/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 9/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Something Like Pointers:Reference Variables
The donuts parameter, in the getOrder function,points to the jellyDonuts variable .
C++ automatically storesthe address of
jellyDonuts in thedonuts parameter.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 10/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointer Variables
• Pointer variables are yet another way using amemory address to work with a piece of data.
• Pointers are more "low-level" than arrays andreference variables.
• This means you are responsible for finding theaddress you want to store in the pointer andcorrectly using it.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 11/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointer Variables
• Definition:int *intptr;
• Read as:“intptr can hold the address of an int”
• Spacing in definition does not matter:
int * intptr; // same as aboveint* intptr; // same as above
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 12/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointer Variables
• Assigning an address to a pointer variable:int *intptr; intptr = #
• Memory layout:num intptr25 0x4a00
address of num : 0x4a00
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 13/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 14/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
The Indirection Operator
• The indirection operator ( * ) dereferencesa pointer.
• It allows you to access the item that thepointer points to.
int x = 25;int *intptr = &x;cout << *intptr << endl;
This prints 25.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 15/215Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 16/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.9-16
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 17/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.3The Relationship Between Arrays
and Pointers
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 18/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
The Relationship BetweenArrays and Pointers• Array name is starting address of array
int vals[] = {4, 7, 11};
cout << vals; // displays
// 0x4a00cout << vals[0]; // displays 4
4 7 11
starting address of vals : 0x4a00
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 19/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
The Relationship BetweenArrays and Pointers• Array name can be used as a pointer
constant:int vals[] = {4, 7, 11};cout << *vals; // displays 4
• Pointer can be used as an array name:int *valptr = vals;cout << valptr[1]; // displays 7
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 20/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.9-20
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 21/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointers in ExpressionsGiven:
int vals[]={4,7,11}, *valptr;valptr = vals;
What is valptr + 1 ? It means (address invalptr ) + (1 * size of an int)cout << *(valptr+1); //displays 7
cout << *(valptr+2); //displays 11
Must use ( ) as shown in the expressions
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 22/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Array Access
• Array elements can be accessed in many ways:
Array access method Example
array name and [] vals[2] = 17;
pointer to array and [] valptr[2] = 17;
array name and subscriptarithmetic
*(vals + 2) = 17;
pointer to array andsubscript arithmetic
*(valptr + 2) = 17;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 23/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Array Access
• Conversion: vals[i] is equivalent to*(vals + i)
• No bounds checking performed on arrayaccess, whether using array name or apointer
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 24/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 9-7
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 25/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.4Pointer Arithmetic
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 26/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointer Arithmetic
• Operations on pointer variables:
9-26
Operation Exampleint vals[]={4,7,11};int *valptr = vals;
++, -- valptr++; // points at 7valptr--; // now points at 4
+, - (pointer and int ) cout << *(valptr + 2); // 11
+=, -=(pointer
and int ) valptr = vals; // points at 4valptr += 2; // points at 11
- (pointer from pointer) cout << valptr – val; // difference//(number of ints) between valptr// and val
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 27/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 9-9
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 28/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.5Initializing Pointers
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 29/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Initializing Pointers
• Can initialize at definition time:int num, *numptr = #int val[3], *valptr = val;
• Cannot mix data types:double cost;int *ptr = &cost; // won ’t work
• Can test for an invalid address for ptr with:if (!ptr) ...
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 30/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.6Comparing Pointers
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 31/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Comparing Pointers
• Relational operators ( <, >= , etc.) can beused to compare addresses in pointers
• Comparing addresses in pointers is not
the same as comparing contents pointedat by pointers:if (ptr1 == ptr2) // compares
// addressesif (*ptr1 == *ptr2) // compares
// contents
9-31
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 32/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.7Pointers as Function Parameters
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 33/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointers as FunctionParameters
• A pointer can be a parameter• Works like reference variable to allow change to
argument from within function
• Requires:1) asterisk * on parameter in prototype and headingvoid getNum(int *ptr); // ptr is pointer to an int2) asterisk * in body to dereference the pointer
cin >> *ptr;3) address as argument to the function getNum(&num); // pass address of num to getNum
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 34/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Example
void swap(int *x, int *y){ int temp;
temp = *x;
*x = *y;*y = temp;
}
int num1 = 2, num2 = -3;swap(&num1, &num2);
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 35/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
(Program Continues)
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 36/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 37/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointers to Constants
• If we want to store the address of aconstant in a pointer, then we need tostore it in a pointer-to-const.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 38/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointers to Constants
• Example: Suppose we have the followingdefinitions:
const int SIZE = 6;const double payRates[SIZE] ={ 18.55, 17.45, 12.85,
14.97, 10.35, 18.89 };
• In this code, payRates is an array ofconstant doubles.
9-38
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 39/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Pointers to Constants
• Suppose we wish to pass the payRates array toa function? Here's an example of how we can doit.
void displayPayRates(const double *rates, int size){
for (int count = 0; count < size; count++){
cout << "Pay rate for employee " << (count + 1)<< " is $" << *(rates + count) << endl;
}}
The parameter, rates, is a pointer to const double .
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 40/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Declaration of a Pointer toConstant
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 41/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Constant Pointers
• A constant pointer is a pointer that isinitialized with an address, and cannotpoint to anything else.
• Example
int value = 22;int * const ptr = &value;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 42/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Constant Pointers
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 43/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Constant Pointers to Constants
• A constant pointer to a constant is: – a pointer that points to a constant – a pointer that cannot point to anything except
what it is pointing to
• Example:int value = 22;const int * const ptr = &value;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 44/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Constant Pointers to Constants
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 45/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.8Dynamic Memory Allocation
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 46/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Dynamic Memory Allocation
• Can allocate storage for a variable whileprogram is running
• Computer returns address of newly
allocated variable• Uses new operator to allocate memory:
double *dptr;
dptr = new double;• new returns address of memory location
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 47/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Dynamic Memory Allocation
• Can also use new to allocate array:const int SIZE = 25;arrayPtr = new double[SIZE];
• Can then use [] or pointer arithmetic to access array:for(i = 0; i < SIZE; i++)
*arrayptr[i] = i * i;or
for(i = 0; i < SIZE; i++)*(arrayptr + i) = i * i;
• Program will terminate if not enough memory available toallocate
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 48/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Releasing Dynamic Memory
• Use delete to free dynamic memory:delete fptr;
• Use [] to free dynamic array:delete [] arrayptr;
• Only use delete with dynamic memory!
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 49/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 50/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 51/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Program 9-14 (Continued)
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 52/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Notice that in line 49 the value 0 is assigned to the sales pointer. It is a
good practice to store 0 in a pointer variable after using delete on it. First,it prevents code from inadvertently using the pointer to access the area of memory that was freed. Second, it prevents errors from occurring if delete is accidentally called on the pointer again. The delete operator is designed to have no effect when used on a null pointer.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 53/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
9.9Returning Pointers from Functions
R i P i f
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 54/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Returning Pointers fromFunctions• Pointer can be the return type of a function:
int* newNum();• The function must not return a pointer to a local
variable in the function.• A function should only return a pointer:
– to data that was passed to the function as anargument, or
– to dynamically allocated memory
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 55/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 9-15
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 56/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 57/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Chapter 10:
Characters, C-Strings, and MoreAbout the string
Class
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 58/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.1Character Testing
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 59/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Character Testing
• require cctype header file
FUNCTION MEANING
isalpha true if arg. is a letter, false otherwise
isalnum true if arg. is a letter or digit, false otherwise
isdigit true if arg. is a digit 0-9, false otherwise
islower true if arg. is lowercase letter, false otherwise
isprint true if arg. is a printable character, false otherwise
ispunct true if arg. is a punctuation character, false otherwiseisupper true if arg. is an uppercase letter, false otherwise
isspace true if arg. is a whitespace character, false otherwise
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 60/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 10-1
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 61/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.2Character Case Conversion
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 62/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Character Case Conversion
• Require cctype header file• Functions:
toupper : if char argument is lowercase letter, return
uppercase equivalent; otherwise, return inputunchangedchar ch1 = 'H';char ch2 = 'e';char ch3 = '!';cout << toupper(ch1); // displays 'H'cout << toupper(ch2); // displays 'E'cout << toupper(ch3); // displays '!'
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 63/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Character Case Conversion
• Functions:tolower : if char argument is uppercase letter, returnlowercase equivalent; otherwise, return inputunchangedchar ch1 = 'H';char ch2 = 'e';char ch3 = '!';cout << tolower(ch1); // displays 'h'cout << tolower(ch2); // displays 'e'cout << tolower(ch3); // displays '!'
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 64/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.3C-Strings
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 65/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
C-Strings
• C-string: sequence of characters stored inadjacent memory locations andterminated by NULL character
• String literal (string constant): sequence ofcharacters enclosed in double quotes " " :
"Hi there!"
H i t h e r e ! \0
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 66/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
C-Strings
• Array of char s can be used to define storage forstring:const int SIZE = 20;char city[SIZE];
• Leave room for NULL at end• Can enter a value using cin or >>
– Input is whitespace-terminated
– No check to see if enough space• For input containing whitespace, and to controlamount of input, use cin.getline()
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 67/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 68/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.4Library Functions for Working with
C-Strings
Library Functions for Working
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 69/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Library Functions for Workingwith C-Strings• Require the cstring header file
• Functions take one or more C-strings asarguments. Can use: – C-string name – pointer to C-string
– literal string
Library Functions for
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 70/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Library Functions forWorking with C-StringsFunctions:
– strlen(str) : returns length of C-string strchar city[SIZE] = "Missoula";
cout << strlen(city); // prints 8– strcat(str1, str2) : appends str2 to the
end of str1char location[SIZE] = "Missoula, ";
char state[3] = "MT";strcat(location, state);// location now has "Missoula, MT"
Library Functions for
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 71/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Library Functions forWorking with C-StringsFunctions:
– strcpy(str1, str2) : copies str2 to str1
const int SIZE = 20;char fname[SIZE] = "Maureen", name[SIZE];strcpy(name, fname);
Note: strcat and strcpy perform no boundschecking to determine if there is enough spacein receiving character array to hold the string itis being assigned.
d
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 72/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
C-string Inside a C-string
Function:– strstr(str1, str2) : finds the first
occurrence of str2 in str1 . Returns a
pointer to match, or NULL if no match.char river[] = "Wabash";char word[] = "aba";cout << strstr(state, word);// displays "abash"
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 73/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.5C-String/Numeric Conversion
Functions
String/Numeric Conversion
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 74/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
gFunctions• require cstdlib header file
FUNCTION PARAMETER ACTION
atoi C-string converts C-string to an int value, returnsthe value
atol C-string converts C-string to a long value, returnsthe value
atof C-string converts C-string to a double value,returns the value
itoa int, C-string,int converts 1 st int parameter to a C-string,stores it in 2 nd parameter. 3 rd parameter isbase of converted value
String/Numeric Conversion
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 75/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
gFunctions
int iNum;long lNum;double dNum;
char intChar[10];iNum = atoi("1234"); // puts 1234 in iNumlNum = atol("5678"); // puts 5678 in lNumdNum = atof("35.7"); // puts 35.7 in dNum
itoa(iNum, intChar, 8); // puts the string// "2322" (base 8 for 1234 10 ) in intChar
String/Numeric Conversion
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 76/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
String/Numeric ConversionFunctions - Notes• if C-string contains non-digits, results are
undefined – function may return result up to non-digit
– function may return 0
• itoa does no bounds checking – make
sure there is enough space to store theresult
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 77/215
Writing Your Own C-StringHandling Functions
10.6
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 78/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.6Writing Your Own C-String
Handling Functions
Writing Your Own C-String
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 79/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Writing Your Own C StringHandling Functions• Designing C-String Handling Functions
– can pass arrays or pointers to char arrays – Can perform bounds checking to ensure
enough space for results – Can anticipate unexpected user input
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 80/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 10-9
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 81/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
From Program 10-10
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 82/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
10.7More About the C++ string
Class
h C Cl
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 83/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
The C++ string Class
• Special data type supports working with strings• #include <string>• Can define string variables in programs:
string firstName, lastName;• Can receive values with assignment operator:
firstName = "George";lastName = "Washington";
• Can be displayed via coutcout << firstName << " " << lastName;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 84/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
I i Obj
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 85/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Input into a string Object
• Use cin >> to read an item into a string:string firstName;cout << "Enter your first name: ";cin >> firstName;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 86/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
I i i Obj
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 87/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Input into a string Object
• Use getline function to put a line ofinput, possibly including spaces, into astring:
string address;cout << "Enter your address: ";getline(cin,address);
i C i
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 88/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string Comparison
• Can use relational operators directly to compare stringobjects:
string str1 = "George",str2 = "Georgia";
if (str1 < str2)cout << str1 << " is less than "
<< str2;
• Comparison is performed similar to strcmp function.Result is true or false
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 89/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Other Definitions of C++
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 90/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string s
Definition Meaning
string name; defines an empty string object
string myname("Chris"); defines a string and initializes it
string yourname(myname); defines a string and initializes itstring aname(myname, 3); defines a string and initializes it with first 3
characters of myname
string verb(myname,3,2); defines a string and initializes it with 2characters from myname starting at position3
string noname('A', 5); defines string and initializes it to 5 'A' s
string Operators
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 91/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string Operators
OPERATOR MEANING
>> extracts characters from stream up to whitespace, insertinto string
<< inserts string into stream
= assigns string on right to string object on left+= appends string on right to end of contents on left
+ concatenates two strings
[] references character in string using array notation
>, >=, <,<=, ==, !=
relational operators for string comparison. Return true orfalse
i O t
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 92/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string Operators
string word1, phrase;string word2 = " Dog";cin >> word1; // user enters "Hot Tamale"
// word1 has "Hot"
phrase = word1 + word2; // phrase has// "Hot Dog"
phrase += " on a bun";for (int i = 0; i < 16; i++)
cout << phrase[i]; // displays// "Hot Dog on a bun"
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 93/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
t i M b F ti
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 94/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string Member Functions
• Are behind many overloaded operators• Categories:
– assignment: assign, copy, data – modification: append, clear, erase, insert,
replace, swap – space management: capacity, empty,
length, resize, size – substrings: find, substr
– comparison: compare• See Table 10-7 for a list of functions
t i Member F nctions
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 95/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
string Member Functions
string word1, word2, phrase;cin >> word1; // word1 is "Hot"word2.assign(" Dog");
phrase.append(word1);phrase.append(word2); // phrase has "Hot Dog"phrase.append(" with mustard relish", 13);
// phrase has "Hot Dog with mustard"phrase.insert(8, "on a bun ");cout << phrase << endl; // displays
// "Hot Dog on a bun with mustard"
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 96/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 97/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Chapter 11:
Structured Data
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 98/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.1Abstract Data Types
Ab t t D t T
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 99/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Abstract Data Types
• A data type that specifies – values that can be stored – operations that can be done on the values
• User of an abstract data type does notneed to know the implementation of thedata type, e.g. , how the data is stored
• ADTs are created by programmers
Abstraction and Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 100/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Abstraction and Data Types
• Abstraction: a definition that capturesgeneral characteristics without details – Ex: An abstract triangle is a 3-sided polygon.
A specific triangle may be scalene, isosceles,or equilateral
• Data Type defines the values that can be
stored in a variable and the operations thatcan be performed on it
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 101/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.2Combining Data into Structures
Combining Data into Structures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 102/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Combining Data into Structures
• Structure: C++ construct that allows multiplevariables to be grouped together
• General Format:
struct <structName
>{type 1 field 1 ;type 2 field 2 ;
. . .};
Example struct Declaration
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 103/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Example struct Declaration
struct Student{
int studentID;
string name;short yearInSchool;double gpa;
};
structure tag
structure members
struct Declaration Notes
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 104/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
struct Declaration Notes
• Must have ; after closing } • struct names commonly begin with
uppercase letter• Multiple fields of same type can be in
comma-separated list:string name,
address;
Defining Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 105/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Defining Variables• struct declaration does not allocate
memory or create variables• To define variables, use structure tag as
type name:Student bill;
studentID
name
yearInSchool
gpa
bill
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 106/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.3Accessing Structure Members
Accessing Structure Members
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 107/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Accessing Structure Members
• Use the dot (.) operator to refer to members ofstruct variables:
cin >> stu1.studentID; getline(cin, stu1.name);stu1.gpa = 3.75;
• Member variables can be used in any manner
appropriate for their data type
11-107
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 108/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 109/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 110/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Displaying a struct Variable
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 111/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Displaying a struct Variable
• To display the contents of a struct variable, must display each fieldseparately, using the dot operator:
cout << bill; // won’t workcout << bill.studentID << endl;
cout << bill.name << endl;cout << bill.yearInSchool;cout << " " << bill.gpa;
Comparing struct Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 112/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Comparing struct Variables
• Cannot compare struct variablesdirectly:
if (bill == william) // won ’t work
• Instead, must compare on a field basis:if (bill.studentID ==
william.studentID) ...
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 113/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.4Initializing a Structure
Initializing a Structure
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 114/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Initializing a Structure
• struct variable can be initialized whendefined:Student s = {11465, "Joan", 2, 3.75};
• Can also be initialized member-by-member after definition:
s.name = "Joan";s.gpa = 3.75;
More on Initializing a Structure
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 115/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
More on Initializing a Structure
• May initialize only some members:Student bill = {14579};
• Cannot skip over members:
Student s = {1234, "John", ,2.83}; // illegal
• Cannot initialize in the structuredeclaration, since this does not allocatememory
Excerpts From Program 11-3
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 116/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Excerpts From Program 11-3
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 117/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.5Arrays of Structures
Arrays of Structures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 118/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
y
• Structures can be defined in arrays• Can be used in place of parallel arrays
const int NUM_STUDENTS = 20;Student stuList[NUM_STUDENTS];
• Individual structures accessible using subscriptnotation
• Fields within structures accessible using dot
notation:cout << stuList[5].studentID;
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 119/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 120/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 121/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 122/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.6Nested Structures
Nested Structures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 123/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Nested Structures
A structure can contain another structure as amember:struct PersonInfo{ string name,
address,city;
};struct Student{ int studentID;
PersonInfo pData;short yearInSchool;double gpa;
};
Members of Nested Structures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 124/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Members of Nested Structures
• Use the dot operator multiple times to referto fields of nested structures:
Student s;s.pData.name = "Joanne";s.pData.city = "Tulsa";
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 125/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.7Structures as Function Arguments
Structures as FunctionA
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 126/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Arguments• May pass members of struct variables to
functions:computeGPA(stu.gpa);
• May pass entire struct variables to functions:showData(stu);• Can use reference parameter if function needs
to modify contents of structure variable
Excerpts from Program 11-6
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 127/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Excerpts from Program 11 6
Structures as FunctionA N
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 128/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Arguments - Notes• Using value parameter for structure can
slow down a program, waste space • Using a reference parameter will speed up
program, but function may change data instructure • Using a const reference parameter
allows read-only access to reference
parameter, does not waste space, speed
Revised showItem Function
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 129/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 130/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.8Returning a Structure from a
Function
Returning a Structure from aF i
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 131/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Function• Function can return a struct :
Student getStudentData(); // prototypestu1 = getStudentData(); // call
• Function must define a local structure – for internal use – for use with return statement
Returning a Structure from aF ti E l
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 132/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Function - ExampleStudent getStudentData(){ Student tempStu;
cin >> tempStu.studentID;getline(cin, tempStu.pData.name);getline(cin, tempStu.pData.address);getline(cin, tempStu.pData.city);cin >> tempStu.yearInSchool;cin >> tempStu.gpa;return tempStu;
}
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 133/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 134/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 135/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 136/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.9Pointers to Structures
Pointers to Structures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 137/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• A structure variable has an address• Pointers to structures are variables that
can hold the address of a structure:
Student *stuPtr;• Can use & operator to assign address:stuPtr = & stu1;
• Structure pointer can be a functionparameter
11-137
Accessing Structure Membersia Pointer Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 138/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
via Pointer Variables• Must use () to dereference pointer
variable, not field within structure:cout << (*stuPtr).studentID;
• Can use structure pointer operator toeliminate () and use clearer notation:
cout << stuPtr->studentID;
11-138
From Program 11-8
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 139/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
g
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 140/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.11Unions
Unions
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 141/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Similar to a struct , but – all members share a single memory location, and – only one member of the union can be used at a time
• Declared using union , otherwise the same asstruct
• Variables defined as for struct variables
Anonymous Union
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 142/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• A union without a union tag:union { ... };
• Must use static if declared outside of a function
• Allocates memory at declaration time
• Can refer to members directly without dot operator
• Uses only one memory location, saves space
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 143/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
11.12Enumerated Data Types
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 144/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• An enumerated data type is a programmer-defined data type. It consists of valuesknown as enumerators , which representinteger constants.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 145/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Example:enum Day { MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
FRIDAY };• The identifiers MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, and FRIDAY ,which are listed inside the braces, areenumerators . They represent the valuesthat belong to the Day data type.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 146/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
enum Day { MONDAY, TUESDAY,WEDNESDAY, THURSDAY,
FRIDAY };
Note that the enumerators are not strings,so they aren’t enclosed in quotes.They are identifiers.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 147/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Once you have created an enumerateddata type in your program, you can definevariables of that type. Example:
Day workDay;
• This statement defines workDay as avariable of the Day type.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 148/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• We may assign any of the enumeratorsMONDAY, TUESDAY, WEDNESDAY,THURSDAY, or FRIDAY to a variable of the
Day type. Example:
workDay = WEDNESDAY;
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 149/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• So, what is an enumerator ?• Think of it as an integer named constant• Internally, the compiler assigns integer
values to the enumerators, beginning at 0.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 150/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
enum Day { MONDAY, TUESDAY,WEDNESDAY, THURSDAY,FRIDAY };
In memory...
MONDAY= 0 TUESDAY = 1
WEDNESDAY= 2 THURSDAY = 3 FRIDAY = 4
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 151/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Using the Day declaration, the followingcode...cout << MONDAY << " "
<< WEDNESDAY << " “ << FRIDAY << endl;
...will produce this output:0 2 4
Assigning an integer to an enum Variable
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 152/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Variable• You cannot directly assign an integer value
to an enum variable. This will not work:
workDay = 3; // Error! • Instead, you must cast the integer:
workDay = static_cast<Day>(3);
Assigning an Enumerator to an int Variable
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 153/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Variable
• You CAN assign an enumerator to an int variable. For example:
int x;x = THURSDAY;
• This code assigns 3 to x .
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 154/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 155/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Program 11-12 (Continued)
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 156/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Enumerated Data Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 157/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Program 11-12 shows enumerators used tocontrol a loop:
// Get the sales for each day.for (index = MONDAY; index <= FRIDAY;index++){
cout << "Enter the sales for day "<< index << ": ";
cin >> sales[index];}
11-157
Anonymous Enumerated Types
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 158/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• An anonymous enumerated type is simplyone that does not have a name. Forexample, in Program 11-13 we could have
declared the enumerated type as:
enum { MONDAY, TUESDAY,WEDNESDAY, THURSDAY,FRIDAY };
Using Math Operators with enum Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 159/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• You can run into problems when trying to perform mathoperations with enum variables. For example:
Day day1, day2; // Define two Day variables.day1 = TUESDAY; // Assign TUESDAY to day1.day2 = day1 + 1;// ERROR! Will not work!
• The third statement will not work because the expressionday1 + 1 results in the integer value 2, and you cannot
store an int in an enum variable.
Using Math Operators with enum Variables
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 160/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Variables
• You can fix this by using a cast to explicitlyconvert the result to Day , as shown here:
// This will work. day2 = static_cast<Day>(day1 + 1);
Using an enum Variable to Stepthrough an Array's Elements
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 161/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Because enumerators are stored in memory asintegers, you can use them as array subscripts.For example:enum Day { MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY };const int NUM_DAYS = 5;double sales[NUM_DAYS];sales[MONDAY] = 1525.0;sales[TUESDAY] = 1896.5;
sales[WEDNESDAY] = 1975.63;sales[THURSDAY] = 1678.33;sales[FRIDAY] = 1498.52;
Using an enum Variable to Stepthrough an Array's Elements
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 162/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Remember, though, you cannot use the ++operator on an enum variable. So, thefollowing loop will NOT work.
Day workDay; // Define a Day variable// ERROR!!! This code will NOT work.for (workDay = MONDAY; workDay <= FRIDAY; workDay++){
cout << "Enter the sales for day "
<< workDay << ": ";cin >> sales[workDay];}
Using an enum Variable to Stepthrough an Array's Elements
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 163/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• You must rewrite the loop’s updateexpression using a cast instead of ++:
for (workDay = MONDAY; workDay <= FRIDAY;workDay = static_cast<Day>(workDay + 1))
{cout << "Enter the sales for day "
<< workDay << ": ";cin >> sales[workDay];
}
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 164/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 165/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Enumerators Must Be UniqueWithin the same Scope
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 166/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Enumerators must be unique within the samescope. For example, an error will result if bothof the following enumerated types aredeclared within the same scope:
enum Presidents { MCKINLEY, ROOSEVELT, TAFT };
enum VicePresidents { ROOSEVELT, FAIRBANKS,SHERMAN };
ROOSEVELT is declared twice.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 167/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 168/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Chapter 12:
Advanced FileOperations
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 169/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.1File Operations
File Operations
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 170/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• File: a set of data stored on a computer,often on a disk drive
• Programs can read from, write to files
• Used in many applications: – Word processing – Databases – Spreadsheets – Compilers
Using Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 171/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
1. Requires fstream header file – use ifstream data type for input files – use ofstream data type for output files – use fstream data type for both input, output
files2. Can use >> , << to read from, write to a file3. Can use eof member function to test for
end of input file
fstream Object
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 172/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• fstream object can be used for either input or output• Must specify mode on the open statement• Sample modes:
ios::in – inputios::out – output
• Can be combined on open call:dFile.open("class.txt", ios::in | ios::out);
File Access Flags
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 173/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Using Files - Example
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 174/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
// copy 10 numbers between files// open the filesfstream infile("input.txt", ios::in);fstream outfile("output.txt", ios::out);
int num;for (int i = 1; i <= 10; i++){
infile >> num; // use the filesoutfile << num;
}infile.close(); // close the filesoutfile.close();
Default File Open Modes
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 175/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
•
ifstream : – open for input only – file cannot be written to
– open fails if file does not exist
• ofstream: – open for output only – file cannot be read from – file created if no file exists – file contents erased if file exists
More File Open Details
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 176/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Can use filename, flags in definition:ifstream gradeList("grades.txt");
• File stream object set to 0 (false ) ifopen failed:
if (!gradeList) ...
• Can also check fail member function todetect file open error:if (gradeList.fail()) ...
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 177/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.2File Output Formatting
File Output Formatting
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 178/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Use the same techniques with file streamobjects as with cout : showpoint,setw(x), showprecision(x), etc.
• Requires iomanip to use manipulators
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 179/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Program 12-3 (Continued)
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 180/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 181/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.3Passing File Stream Objects to
Functions
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 182/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 183/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 184/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 185/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 186/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.4More Detailed Error Testing
More Detailed Error Testing
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 187/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Can examine error state bits to determine streamstatus
• Bits tested/cleared by stream member functions
ios::eofbit set when end of file detected
ios::failbit set when operation failed
ios::hardfail set when error occurred and no recovery
ios::badbit set when invalid operation attempted
ios::goodbit set when no other bits are set
Member Functions / Flags
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 188/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
eof() true if eofbit set, false otherwise
fail() true if failbit or hardfail set, false otherwise
bad() true if badbit set, false otherwise
good() true if goodbit set, false otherwise
clear() clear all flags (no arguments), or clear a specific flag
From Program 12-6
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 189/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 190/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.5Member Functions for Reading
and Writing Files
Member Functions for Readingand Writing Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 191/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Functions that may be used for input withwhitespace, to perform single characterI/O, or to return to the beginning of an inputfile
• Member functions:getline : reads input including whitespaceget : reads a single characterput : writes a single character
The getline Function
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 192/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Three arguments: – Name of a file stream object – Name of a string object – Delimiter character of your choice
– Examples, using the file stream object myFile , and the string objects name and address: getline(myFile, name);getline(myFile, address, '\t');
– If left out, '\n' is default for third argument
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 193/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 194/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
Single Character I/O
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 195/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
•
get : read a single character from a filechar letterGrade;gradeFile.get(letterGrade);
Will read any character, including whitespace
• put : write a single character to a filereportFile.put(letterGrade);
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 196/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.6Working with Multiple Files
Working with Multiple Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 197/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• Can have more than file open at a time ina program
• Files may be open for input or output
• Need to define file stream object for eachfile
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 198/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 199/215
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 200/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 201/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.7Binary Files
Binary Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 202/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-202
• Binary file contains unformatted, non-ASCIIdata
• Indicate by using binary flag on open:inFile.open("nums.dat", ios::in |ios::binary);
Binary FilesU d d i i t d f
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 203/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-203
• Use read and write instead of << , >>char ch;// read in a letter from file inFile.read(&ch, sizeof(ch));
// send a character to a fileoutFile.write(&ch, sizeof(ch));
address of where to putthe data being read in.The read function expectsto read char s
how many bytes toread from the file
Binary Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 204/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
• To read , write non-character data, must use atypecast operator to treat the address of the dataas a character address int num;
// read in a binary number from a file inFile.read(reinterpret_cast<char *>&num,
sizeof(num));
// send a binary value to a fileoutf.write(reinterpret_cast<char *>&num,
sizeof(num));
treat the address of num asthe address of a char
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 205/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.8Creating Records with Structures
Creating Records withStructures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 206/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-206
• Can write structures to, read structuresfrom files
• To work with structures and files, – use ios::binary file flag upon open – use read , write member functions
Creating Records withStructures
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 207/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-207
struct TestScore{
int studentId;double score;
char grade;};TestScore oneTest;...
// write out oneTest to a filegradeFile.write(reinterpret_cast<char *>(&oneTest), sizeof(oneTest));
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 208/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.9Random-Access Files
Random-Access Files
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 209/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-209
• Sequential access: start at beginning offile and go through data in file, in order,to end
– to access 100th
entry in file, go through 99preceding entries first• Random access: access data in a file in
any order – can access 100 th entry directly
Random Access MemberFunctions
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 210/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-210
• seekg (seek get): used with files open forinput
• seekp (seek put): used with files open foroutput
• Used to go to a specific position in a file
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 211/215
Important Note on RandomAccess
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 212/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-212
• If eof is true, it must be cleared beforeseekg or seekp :
gradeFile.clear();gradeFile.seekg(0L, ios::beg);// go to the beginning of the file
Random Access Information
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 213/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12-213
•
tellg member function: return currentbyte position in input filelong int whereAmI;whereAmI = inData.tellg();
• tellp member function: return currentbyte position in output file
whereAmI = outData.tellp();
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 214/215
Copyright © 2012 Pearson Education, Inc.Copyright © 2012 Pearson Education, Inc.
12.10Opening a File for
Both Input and Output
Opening a File forBoth Input and Output
8/2/2019 Midterm Slides 9-12
http://slidepdf.com/reader/full/midterm-slides-9-12 215/215
• File can be open for input and output simultaneously• Supports updating a file: – read data from file into memory – update data – write data back to file
• Use fstream for file object definition:fstream gradeList("grades.dat",
ios::in | ios::out);• Can also use ios::binary flag for binary data