+ All Categories
Home > Documents > Midterm Slides 9-12

Midterm Slides 9-12

Date post: 05-Apr-2018
Category:
Upload: billykwan13
View: 219 times
Download: 0 times
Share this document with a friend
215
Copyright © 2012 Pearson Education, Inc. Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers 
Transcript
Page 1: Midterm Slides 9-12

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

Page 2: Midterm Slides 9-12

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

Page 3: Midterm Slides 9-12

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 << &num; // prints address

// in hexadecimal

Page 4: Midterm Slides 9-12

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

Page 5: Midterm Slides 9-12

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

Page 6: Midterm Slides 9-12

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);

Page 7: Midterm Slides 9-12

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 .

Page 8: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 8/215

Page 9: Midterm Slides 9-12

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.

Page 10: Midterm Slides 9-12

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.

Page 11: Midterm Slides 9-12

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

Page 12: Midterm Slides 9-12

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 = &num;

• Memory layout:num intptr25 0x4a00

address of num : 0x4a00

Page 13: Midterm Slides 9-12

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.

Page 14: Midterm Slides 9-12

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.

Page 15: Midterm Slides 9-12

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.

Page 16: Midterm Slides 9-12

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

Page 17: Midterm Slides 9-12

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

Page 18: Midterm Slides 9-12

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

Page 19: Midterm Slides 9-12

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

Page 20: Midterm Slides 9-12

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

Page 21: Midterm Slides 9-12

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

Page 22: Midterm Slides 9-12

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;

Page 23: Midterm Slides 9-12

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

Page 24: Midterm Slides 9-12

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

Page 25: Midterm Slides 9-12

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

Page 26: Midterm Slides 9-12

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

Page 27: Midterm Slides 9-12

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

Page 28: Midterm Slides 9-12

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

Page 29: Midterm Slides 9-12

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 = &num;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) ...

Page 30: Midterm Slides 9-12

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

Page 31: Midterm Slides 9-12

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

Page 32: Midterm Slides 9-12

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

Page 33: Midterm Slides 9-12

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

Page 34: Midterm Slides 9-12

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);

Page 35: Midterm Slides 9-12

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)

Page 36: Midterm Slides 9-12

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.

Page 37: Midterm Slides 9-12

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.

Page 38: Midterm Slides 9-12

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

Page 39: Midterm Slides 9-12

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 .

Page 40: Midterm Slides 9-12

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

Page 41: Midterm Slides 9-12

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;

Page 42: Midterm Slides 9-12

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

Page 43: Midterm Slides 9-12

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;

Page 44: Midterm Slides 9-12

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

Page 45: Midterm Slides 9-12

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

Page 46: Midterm Slides 9-12

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

Page 47: Midterm Slides 9-12

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

Page 48: Midterm Slides 9-12

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!

Page 49: Midterm Slides 9-12

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.

Page 50: Midterm Slides 9-12

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.

Page 51: Midterm Slides 9-12

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)

Page 52: Midterm Slides 9-12

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.

Page 53: Midterm Slides 9-12

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

Page 54: Midterm Slides 9-12

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

Page 55: Midterm Slides 9-12

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

Page 56: Midterm Slides 9-12

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.

Page 57: Midterm Slides 9-12

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

Page 58: Midterm Slides 9-12

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

Page 59: Midterm Slides 9-12

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

Page 60: Midterm Slides 9-12

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

Page 61: Midterm Slides 9-12

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

Page 62: Midterm Slides 9-12

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 '!'

Page 63: Midterm Slides 9-12

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 '!'

Page 64: Midterm Slides 9-12

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

Page 65: Midterm Slides 9-12

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

Page 66: Midterm Slides 9-12

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()

Page 67: Midterm Slides 9-12

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.

Page 68: Midterm Slides 9-12

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

Page 69: Midterm Slides 9-12

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

Page 70: Midterm Slides 9-12

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

Page 71: Midterm Slides 9-12

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

Page 72: Midterm Slides 9-12

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"

Page 73: Midterm Slides 9-12

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

Page 74: Midterm Slides 9-12

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

Page 75: Midterm Slides 9-12

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

Page 76: Midterm Slides 9-12

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

Page 77: Midterm Slides 9-12

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

Page 78: Midterm Slides 9-12

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

Page 79: Midterm Slides 9-12

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

Page 80: Midterm Slides 9-12

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

Page 81: Midterm Slides 9-12

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

Page 82: Midterm Slides 9-12

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

Page 83: Midterm Slides 9-12

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;

Page 84: Midterm Slides 9-12

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

Page 85: Midterm Slides 9-12

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;

Page 86: Midterm Slides 9-12

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

Page 87: Midterm Slides 9-12

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

Page 88: Midterm Slides 9-12

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

Page 89: Midterm Slides 9-12

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++

Page 90: Midterm Slides 9-12

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

Page 91: Midterm Slides 9-12

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

Page 92: Midterm Slides 9-12

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"

Page 93: Midterm Slides 9-12

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

Page 94: Midterm Slides 9-12

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

Page 95: Midterm Slides 9-12

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"

Page 96: Midterm Slides 9-12

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.

Page 97: Midterm Slides 9-12

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

Page 98: Midterm Slides 9-12

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

Page 99: Midterm Slides 9-12

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

Page 100: Midterm Slides 9-12

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

Page 101: Midterm Slides 9-12

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

Page 102: Midterm Slides 9-12

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

Page 103: Midterm Slides 9-12

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

Page 104: Midterm Slides 9-12

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

Page 105: Midterm Slides 9-12

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

Page 106: Midterm Slides 9-12

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

Page 107: Midterm Slides 9-12

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

Page 108: Midterm Slides 9-12

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.

Page 109: Midterm Slides 9-12

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.

Page 110: Midterm Slides 9-12

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

Page 111: Midterm Slides 9-12

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

Page 112: Midterm Slides 9-12

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) ...

Page 113: Midterm Slides 9-12

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

Page 114: Midterm Slides 9-12

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

Page 115: Midterm Slides 9-12

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

Page 116: Midterm Slides 9-12

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

Page 117: Midterm Slides 9-12

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

Page 118: Midterm Slides 9-12

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;

Page 119: Midterm Slides 9-12

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.

Page 120: Midterm Slides 9-12

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.

Page 121: Midterm Slides 9-12

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.

Page 122: Midterm Slides 9-12

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

Page 123: Midterm Slides 9-12

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

Page 124: Midterm Slides 9-12

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";

Page 125: Midterm Slides 9-12

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

Page 126: Midterm Slides 9-12

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

Page 127: Midterm Slides 9-12

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

Page 128: Midterm Slides 9-12

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

Page 129: Midterm Slides 9-12

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.

Page 130: Midterm Slides 9-12

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

Page 131: Midterm Slides 9-12

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

Page 132: Midterm Slides 9-12

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;

}

Page 133: Midterm Slides 9-12

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.

Page 134: Midterm Slides 9-12

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.

Page 135: Midterm Slides 9-12

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.

Page 136: Midterm Slides 9-12

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

Page 137: Midterm Slides 9-12

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

Page 138: Midterm Slides 9-12

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

Page 139: Midterm Slides 9-12

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

Page 140: Midterm Slides 9-12

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

Page 141: Midterm Slides 9-12

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

Page 142: Midterm Slides 9-12

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

Page 143: Midterm Slides 9-12

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

Page 144: Midterm Slides 9-12

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

Page 145: Midterm Slides 9-12

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

Page 146: Midterm Slides 9-12

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

Page 147: Midterm Slides 9-12

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

Page 148: Midterm Slides 9-12

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

Page 149: Midterm Slides 9-12

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

Page 150: Midterm Slides 9-12

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

Page 151: Midterm Slides 9-12

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

Page 152: Midterm Slides 9-12

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

Page 153: Midterm Slides 9-12

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 .

Page 154: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 154/215

Page 155: Midterm Slides 9-12

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)

Page 156: Midterm Slides 9-12

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

Page 157: Midterm Slides 9-12

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

Page 158: Midterm Slides 9-12

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

Page 159: Midterm Slides 9-12

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

Page 160: Midterm Slides 9-12

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

Page 161: Midterm Slides 9-12

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

Page 162: Midterm Slides 9-12

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

Page 163: Midterm Slides 9-12

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];

}

Page 164: Midterm Slides 9-12

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.

Page 165: Midterm Slides 9-12

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

Page 166: Midterm Slides 9-12

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.

Page 167: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 167/215

Page 168: Midterm Slides 9-12

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

Page 169: Midterm Slides 9-12

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

Page 170: Midterm Slides 9-12

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

Page 171: Midterm Slides 9-12

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

Page 172: Midterm Slides 9-12

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

Page 173: Midterm Slides 9-12

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

Page 174: Midterm Slides 9-12

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

Page 175: Midterm Slides 9-12

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

Page 176: Midterm Slides 9-12

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()) ...

Page 177: Midterm Slides 9-12

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

Page 178: Midterm Slides 9-12

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

Page 179: Midterm Slides 9-12

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)

Page 180: Midterm Slides 9-12

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.

Page 181: Midterm Slides 9-12

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

Page 182: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 182/215

Page 183: Midterm Slides 9-12

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.

Page 184: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 184/215

Page 185: Midterm Slides 9-12

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.

Page 186: Midterm Slides 9-12

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

Page 187: Midterm Slides 9-12

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

Page 188: Midterm Slides 9-12

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

Page 189: Midterm Slides 9-12

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.

Page 190: Midterm Slides 9-12

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

Page 191: Midterm Slides 9-12

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

Page 192: Midterm Slides 9-12

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

Page 193: Midterm Slides 9-12

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.

Page 194: Midterm Slides 9-12

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

Page 195: Midterm Slides 9-12

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);

Page 196: Midterm Slides 9-12

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

Page 197: Midterm Slides 9-12

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

Page 198: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 198/215

Page 199: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 199/215

Page 200: Midterm Slides 9-12

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.

Page 201: Midterm Slides 9-12

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

Page 202: Midterm Slides 9-12

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

Page 203: Midterm Slides 9-12

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

Page 204: Midterm Slides 9-12

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

Page 205: Midterm Slides 9-12

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

Page 206: Midterm Slides 9-12

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

Page 207: Midterm Slides 9-12

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));

Page 208: Midterm Slides 9-12

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

Page 209: Midterm Slides 9-12

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

Page 210: Midterm Slides 9-12

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

Page 211: Midterm Slides 9-12

8/2/2019 Midterm Slides 9-12

http://slidepdf.com/reader/full/midterm-slides-9-12 211/215

Important Note on RandomAccess

Page 212: Midterm Slides 9-12

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

Page 213: Midterm Slides 9-12

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();

Page 214: Midterm Slides 9-12

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

Page 215: Midterm Slides 9-12

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


Recommended