Chapter 5 I/O Streams as an Introduction to Objects and Classes Goals:Goals: To determine how to use external files for input and output To determine.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Chapter 10.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 8 Arrays and Strings
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 7.4 Multidimensional Arrays Goals: To examine the basics of multidimensional arrays in C++ To examine the basics of multidimensional arrays in.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers *, &, array similarities, functions, sizeof.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Chapter 8CS 140 Using The C++ Standard string Class #include #include using namespace std; void main() { string firstName = "Fred"; string lastName =
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 11 Strings & Multidimensional Arrays Goals: To introduce the idea of character strings as arrays To introduce the idea of character strings as.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Objectives You should be able to describe: One-Dimensional Arrays
Bill Tucker Austin Community College COSC 1315
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
User-Written Functions
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Problems With Character Arrays
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays Kingdom of Saudi Arabia
Engineering Problem Solving with C++, Etter
Chapter 2: Introduction to C++.
7 Arrays.
Arrays Arrays A few types Structures of related data items
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Chapter 5 I/O Streams as an Introduction to Objects and Classes Goals:Goals: To determine how to use external files for input and output To determine how to use external files for input and output To investigate means by which file output can be formatted To investigate means by which file output can be formatted To examine how to use I/O streams as function arguments To examine how to use I/O streams as function arguments To introduce the concept of end-of-file for external input To introduce the concept of end-of-file for external input To explore the nuances of character I/O with get & put To explore the nuances of character I/O with get & put Chapter 5 I/O Streams

Chapter 5CS 140Page 142 #include using namespace std; bool userWantsGrosses(); void outputTotalGross(double gross); void main() { int dayCount = 0; double dailyGross; double totalGross = 0.0; ifstream fileContainingGrosses; if (userWantsGrosses()) { fileContainingGrosses.open("GrossFile.txt"); while (dayCount < 365) { dayCount++; fileContainingGrosses >> dailyGross; totalGross += dailyGross; } fileContainingGrosses.close(); outputTotalGross(totalGross); } else cout << "Well, why did you bother " << "executing this program, " << "you goof?" << endl << endl; return; } Input Files When a program needs to retrieve a stream of data from an external source other than the keyboard, it may use an input file stream. This library enables the use of external files. The declaration of an ifstream variable. Opening the input file in the current directory, using the filename GrossFile.txt. Reading the next value from the input file. Closing the input file. Note that the file name is not specified for closing.

Chapter 5CS 140Page 143 bool userWantsGrosses() { char yOrN; cout << "Would you like to compute the " << year\'s grosses? (Enter Y or N) "; cin >> yOrN; while ((yOrN != 'y') && (yOrN != 'Y') && (yOrN != 'n') && (yOrN != 'N')) { cout << "Your response must be the " << "letter \'Y\' or the letter \'N\'." << " Please try again: "; cin >> yOrN; } return ((yOrN == 'y') || (yOrN == 'Y')); } void outputTotalGross(double gross) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "The total gross is $" << gross << endl << endl; } Contents of GrossFile.txt Resulting Output

Chapter 5CS 140Page 144 #include using namespace std; double newGross(); void main() { ofstream fileContainingGrosses; fileContainingGrosses.open("GrossFile.txt"); fileContainingGrosses.setf(ios::fixed); fileContainingGrosses.setf(ios::showpoint); fileContainingGrosses.precision(2); for (int i = 1; i <= 365; i++) { fileContainingGrosses << newGross(); if (i % 10 == 0) fileContainingGrosses << endl; else fileContainingGrosses << " "; } fileContainingGrosses.close(); return; } Output Files When a program needs to deliver a stream of data to an external destination other than the monitor, it may use an output file stream. This library enables the use of external files. The declaration of an ofstream variable. Opening the output file in the current directory, using the filename GrossFile.txt. Writing the next value to the output file. Closing the output file. Note that the file name is not specified for closing. Formatting floating- point output to the file. Output operations are handled the same as with cout.

Chapter 5CS 140Page 145 double newGross() { static bool firstTime = true; long int randomNumberSeed; double lowerBound = ; double upperBound = ; if (firstTime) { time(&randomNumberSeed); srand(randomNumberSeed); firstTime = false; } return (lowerBound + (upperBound - lowerBound) * (double(rand()) / 32769)); } Note that this program produces a 365-value output file that can be used as an input file in the previous example.

Chapter 5CS 140Page 146 Passing Stream Parameters When passing an input or output stream to a function, make sure to pass it by reference. After being opened, the input stream keeps track of how much of the file has been read, and this will probably be changed inside the function to which the stream is passed. (Otherwise, why bother passing the stream?) After being opened, the output stream buffers the data being written to it, and the contents of this buffer will probably change inside the called function. (Again, why else would the stream be passed?)

Chapter 5CS 140Page 147 #include using namespace std; double computeMonthlyGross(ifstream &inputFile, int monthNbr); void outputMonthlyGross(ofstream &outputFile, int monthNbr, double gross); void main() { int month; char dailyGrossFileName[50]; ifstream dailyGrossFile; char monthlyGrossFileName[50]; ofstream monthlyGrossFile; cout << "Enter the name of the file containing the daily gross amounts: "; cin >> dailyGrossFileName; dailyGrossFile.open(dailyGrossFileName); assert(!dailyGrossFile.fail()); cout << endl << endl; cout << "Enter the name of the file that will contain the monthly gross amounts: "; cin >> monthlyGrossFileName; monthlyGrossFile.open(monthlyGrossFileName); assert(!monthlyGrossFile.fail()); cout << endl << endl; monthlyGrossFile.setf(ios::fixed); monthlyGrossFile.setf(ios::showpoint); monthlyGrossFile.precision(2); for (month = 1; month <= 12; month++) outputMonthlyGross(monthlyGrossFile, month, computeMonthlyGross(dailyGrossFile, month)); dailyGrossFile.close(); monthlyGrossFile.close(); return; } Notice how the streams are passed by reference. An assert statement is used to terminate the program if the asserted condition is not true.

Chapter 5CS 140Page 148 double computeMonthlyGross(ifstream &inputFile, int monthNbr) { int monthLength, dayNbr; double dayGross, monthGross = 0.0; if (monthNbr == 2) monthLength = 28; else if ((monthNbr == 4) || (monthNbr == 6) || (monthNbr == 9) || (monthNbr == 11)) monthLength = 30; else monthLength = 31; for (dayNbr = 1; dayNbr <= monthLength; dayNbr++) { inputFile >> dayGross; monthGross += dayGross; } return monthGross; } void outputMonthlyGross(ofstream &outputFile, int monthNbr, double gross) { static double annualGross = 0.00; outputFile << "MONTH #" << monthNbr << endl; outputFile << '$' << gross << endl << endl; annualGross += gross; if (monthNbr == 12) { outputFile << "ANNUAL TOTAL" << endl; outputFile << '$' << annualGross << endl << endl; } return; } MONTH #7 $ MONTH #8 $ MONTH #9 $ MONTH #10 $ MONTH #11 $ MONTH #12 $ ANNUAL TOTAL $ MONTH #1 $ MONTH #2 $ MONTH #3 $ MONTH #4 $ MONTH #5 $ MONTH #6 $ Final contents of Summary.txt. Sample interactive session

Chapter 5CS 140Page 149 #include using namespace std; void main() { double tooCold, tooHot; double lowTemp, highTemp; int month, day, year; char dummyChar; int lowCount = 0, highCount = 0; ifstream weatherFile; cout << "What temperature is " << "considered too cold " << "(in degrees)? "; cin >> tooCold; Using eof The format of an input file must be known in advance. But the length of the input file doesn’t have to be set in stone! The format of an input file must be known in advance. But the length of the input file doesn’t have to be set in stone! cout << "What temperature is " << "considered too hot " << "(in degrees)? "; cin >> tooHot; weatherFile.open("Temps.txt"); weatherFile >> month; while (!weatherFile.eof()) { weatherFile >> dummyChar; weatherFile >> day; weatherFile >> dummyChar; weatherFile >> year; weatherFile >> lowTemp; if (lowTemp <= tooCold) lowCount++; weatherFile >> highTemp; if (highTemp >= tooHot) highCount++; weatherFile >> month; } weatherFile.close(); cout << lowCount << " COLD DAYS" << endl; cout << highCount << " HOT DAYS" << endl << endl; return; } Whenever an input operation fails to retrieve a new value, the input file’s eof is set to true.

Chapter 5CS 140Page 150 1/3/ /7/ /11/ /19/ /27/ /4/ /6/ /10/ /14/ /18/ /24/ /2/ /6/ /11/ /17/ /22/ /27/ /3/ /8/ /12/ /19/ /27/ Contents of Temps.txt Resulting Output 5/1/ /7/ /12/ /19/ /27/ /31/ /3/ /7/ /13/ /17/ /26/ /30/ /2/ /8/ /11/ /17/ /28/ /3/ /8/ /12/ /16/ /23/ /29/ /2/ /5/ /12/ /18/ /23/ /29/ /4/ /8/ /15/ /21/ /26/ /1/ /6/ /13/ /18/ /25/ /30/ /3/ /7/ /13/ /17/ /22/ /28/ Notice that the program assumed that the format of each line in the input file was an integer month, followed by a single character, then an integer day, followed by another character, then an integer year, followed by some white space, and, finally, an integer low temperature and an integer high temperature.

Chapter 5CS 140Page 151 Character I/O Input files have a built-in “member function” called get to facilitate reading characters. Similarly, output files have a built-in “member function” called put to facilitate writing characters. Input files have a built-in “member function” called get to facilitate reading characters. Similarly, output files have a built-in “member function” called put to facilitate writing characters. #include using namespace std; const int MAX_FILENAME_LENGTH = 50; bool isWhiteSpace(char ch); void main() { ifstream originalFile; ofstream revisedFile; char originalFileName[MAX_FILENAME_LENGTH]; char revisedFileName[MAX_FILENAME_LENGTH]; char currentCharacter; bool justHadWhiteSpace = false; cout << "Enter the name of the file " << "containing the original text: "; cin >> originalFileName; cout << "Enter the name of the where " << " the revised text will be stored: "; cin >> revisedFileName; originalFile.open(originalFileName); revisedFile.open(revisedFileName);

Chapter 5CS 140Page 152 originalFile.get(currentCharacter); while (!originalFile.eof()) { if (isWhiteSpace(currentCharacter)) { if (!justHadWhiteSpace) { revisedFile << endl; justHadWhiteSpace = true; } else { justHadWhiteSpace = false; revisedFile.put(currentCharacter); } originalFile.get(currentCharacter); } originalFile.close(); revisedFile.close(); return; } bool isWhiteSpace(char ch) { return ((ch == ' ') || (ch == '\a') || (ch == '\b') || (ch == '\n') || (ch == '\r') || (ch == '\t')); } #include #include using namespace std; const int MAX_FILENAME_LENGTH = 50; bool isWhiteSpace(char ch); void main() { ifstream originalFile; ofstream revisedFile; char originalFileName[MAX_FILENAME_LENGTH] ; char revisedFileName[MAX_FILENAME_LENGTH];  Beginning of the output file Lexical.txt Input one character Output one character Sample interactive session

Chapter 10 Arrays Goals: To introduce the concept of array variables To introduce the concept of array variables To demonstrate how for-loops are used to traverse arrays To demonstrate how for-loops are used to traverse arrays To illustrate how arrays can be initialized in C++ To illustrate how arrays can be initialized in C++ To demonstrate how arrays can be used as parameters To demonstrate how arrays can be used as parameters To examine common array operations (sorting & searching) To examine common array operations (sorting & searching) To explain how arrays are stored in RAM To explain how arrays are stored in RAM To examine the basics of multidimensional arrays in C++ To examine the basics of multidimensional arrays in C++

Chapter 10CS 140Page 154 Array Variables When dealing with several values of the same type, which are used for similar purposes within a program, it is often convenient to use a single variable to hold the values. int hourlyReading[24]; This variable declaration reserves space in RAM for 24 integer values, which are referred to within the program as hourlyReading[0] through hourlyReading[23].

Chapter 10CS 140Page 155 #include using namespace std; void main() { int hourlyReading[24]; int i; for (i = 0; i < 24; i++) { cout << setw(2) << (i % ) << " o\'clock reading: " << hourlyReading[i]; if (i % 3 == 2) cout << endl; else cout << '\t'; } for (i = 0; i < 24; i++) hourlyReading[i] = -1; hourlyReading[3] = 300; hourlyReading[7] = 700; hourlyReading[9] = 900; hourlyReading[12] = 1200; hourlyReading[20] = 2000; hourlyReading[23] = 2300; cout << endl << endl; for (i = 0; i < 24; i++) { cout << setw(2) << (i % ) << " o\'clock reading: " << setw(4) << hourlyReading[i]; if (i % 3 == 2) cout << endl; else cout << '\t'; } cout << endl; } Notice that the first value in the array is indexed at 0, not 1! Assignment statements may be used with one value in the array, but not with the whole array! One value in the array may be output, but not the whole array at once!

Chapter 10CS 140Page 156 #include using namespace std; void main() { double highVal[10]; double newVal; int lowValIndex; int nbrOfVals = 0; int i; ifstream valFile; valFile.open("values.txt"); valFile >> newVal; while (!valFile.eof()) { if (nbrOfVals < 10) { highVal[nbrOfVals] = newVal; nbrOfVals++; } else { lowValIndex = 0; for (i = 0; i < 10; i++) if (highVal[i] < highVal[lowValIndex]) lowValIndex = i; if (newVal > highVal[lowValIndex]) highVal[lowValIndex] = newVal; } valFile >> newVal; } valFile.close(); cout << setw(20) << "Highest Values" << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(5); for (i = 0; i < nbrOfVals; i++) cout << setw(17) << highVal[i] << endl; cout << endl; return; } Contents of values.txt Resulting Output

Chapter 10CS 140Page 157 ? ? ? ? ? ? ? ? ? ? If the array is already full, then find the smallest entry in the array and, if it’s smaller than the new value, do a replacement! If the array isn’t already full (i.e., if nbrOfVals does not equal 10), then just insert at the end of the list!

Chapter 10CS 140Page byte per char; 12 bytes total What’s Happening in Memory? When an array variable is declared, the size of the array and the number of bytes required for one variable of the designated type are multiplied. The product is the number of consecutive bytes allocated for the array variable. int weekdayTotal[5]; char password[12]; 4 bytes per int; 20 bytes total RAM weekdayTotal ’s memory password ’s memory

Chapter 10CS 140Page 159 Improper Indexing The compiler may not detect a problem when an array is indexed improperly, but an error may occur during execution! #include using namespace std; void main() { int twoPower[25]; int i; for (i = 0; i <= 35; i += 1) { twoPower[i] = int(pow(2,i)); cout << setw(2) << i << ": "; cout << twoPower[i] << endl; } return; }

Chapter 10CS 140Page 160 More Improper Indexing It’s possible that no error will be detected, even during execution, but that still doesn’t mean that the program will work! #include using namespace std; void main() { int nbr = 0; int val = 0; int twoPower[5]; int i; for (i = 0; i <= 7; i += 1) { twoPower[i] = int(pow(2,i)); cout << setw(2) << i << ": "; cout << twoPower[i] << endl; cout << "nbr equals: " << nbr << endl; cout << “val equals: " << val << endl << endl; } return; } Notice how the nbr variable got assigned a new value by mistake? Apparently, nbr is being held in the RAM position right close to the last entry in the twoPower array. Since the system sees that that memory is being used by the program, it doesn’t object to loading it with a value!

Chapter 10CS 140Page 161 Array Initialization While assignment operators cannot normally be used to assign values to entire arrays, they can be used to initialize arrays when they’re being declared. #include using namespace std; void main() { int firstIntList[10] = {0}; int otherIntList[10] = {7}; int thirdIntList[10] = {5,4,3,2}; int finalIntList[] = {0,1,2,3,4,5,6,7,8,9}; double firstDubList[10] = {0.0}; double finalDubList[10] = {1.2, 2.3, 3.4, 4.5, 5.6}; char firstCharList[10] = {'X'}; char finalCharList[10] = {'A','E','I','O','U'}; int i; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); for (i = 0; i < 10; i++) cout << setw(2) << firstIntList[i] << setw(2) << otherIntList[i] << setw(2) << thirdIntList[i] << setw(2) << finalIntList[i] << setw(5) << firstDubList[i] << setw(5) << finalDubList[i] << setw(2) << firstCharList[i] << setw(2) << finalCharList[i] << endl; cout << endl; return; } 1) If the array size is specified and the number of initialized values is too low, all remaining slots are filled with zeroes. 2) If the array size is unspecified, then it’s set to the number of initialized values. 1 2

Chapter 10CS 140Page 162 Passing Array Entries to Functions Array entries may be passed to functions by value or by reference, just like regular variables. #include using namespace std; const double MAX_GROSS = ; double skim(double &gross); void main() { double grossList[365]; ifstream grossFile; ofstream newGrossFile; double embezzlement = 0.0; int i; grossFile.open("GrossFile.txt"); for (i = 0; i < 365; i++) grossFile >> grossList[i]; grossFile.close(); newGrossFile.open("GrossFile.txt"); newGrossFile.setf(ios::fixed); newGrossFile.setf(ios::showpoint); newGrossFile.precision(2); for (i = 0; i < 365; i++) { embezzlement += skim(grossList[i]); newGrossFile << grossList[i]; if (i % 10 == 9) newGrossFile << endl; else newGrossFile << " "; } newGrossFile.close(); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Amount embezzled: $" << embezzlement << endl << endl; return; } double skim(double &gross) { double skimAmt = 0.0; if (gross > MAX_GROSS) { skimAmt = gross - MAX_GROSS; gross = MAX_GROSS; } return skimAmt; } Since the parameter was passed by reference, the alterations are actually being made to the value in the array!

Chapter 10CS 140Page Original contents of GrossFile.txt : Final contents of GrossFile.txt :

Chapter 10CS 140Page 164 Another Example #include using namespace std; const int LIST_SIZE = 10; bool isPowerOfTwo(int value); void main() { int favoriteNbr[LIST_SIZE] = {13,16,21,29,32,35,50,75,95,100}; int i; int powerOfTwoCount = 0; for (i = 0; i < LIST_SIZE; i++) { if (isPowerOfTwo(favoriteNbr[i])) powerOfTwoCount++; } cout << "The List:" << endl; for (i = 0; i < LIST_SIZE; i++) cout << favoriteNbr[i] << endl; cout << endl << powerOfTwoCount << " are powers of two!" << endl << endl; return; } bool isPowerOfTwo(int value) { while ((value % 2 == 0) && (value > 1)) value /= 2; return (value == 1); } Setting up a constant for the array size simplifies code modification if a different size is needed later. Since the parameter was passed by value, the alterations are made to the value of the copy, not to the value in the array!

Chapter 10CS 140Page 165 Passing An Entire Array To A Function An entire array may be passed to a function as a parameter, but only the memory location of the array is actually passed. Thus, an array cannot be passed by value; it is essentially passed by reference, but without the ampersand marking it as passed- by-reference. ////////////////////////////////////////////////////// // This program retrieves a list of test scores // // from a user-specified input file. These scores // // are sorted and averaged. Output includes the // // presorted and sorted lists, as well as the mean. // ////////////////////////////////////////////////////// #include using namespace std; const int MAX_LIST_SIZE = 50; void inputList(int list[], int &listSize); void outputList(const int list[], int listSize); void sortList(int list[], int listSize); double averageList(const int list[], int listSize); Each function prototype with an array parameter must specify the type and use brackets to specify that it’s an array, but since the parameter is essentially passed by reference, its size need not be specified here. Since array parameters cannot be passed by value, there is a danger that they might be inadvertently altered within a function. To avoid this, they can be modified with the const designation, which prohibits the function from changing their values.

Chapter 10CS 140Page 166 // The main function supervises the input, output, // // sorting, and averaging of a list of test scores, // // including the output of the list's mean value. // void main() { int testScore[MAX_LIST_SIZE]; int nbrStudents; inputList(testScore, nbrStudents); cout << endl << "Presorted Scores:" << endl; outputList(testScore, nbrStudents); sortList(testScore, nbrStudents); cout << endl << "Sorted Scores:" << endl; outputList(testScore, nbrStudents); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << endl << "The mean score is " << averageList(testScore, nbrStudents) << endl << endl; return; } When actually calling the function, the type of the array parameter is not specified in the function call. Similarly, the square brackets designating the argument as an array and the size of the array are not specified in the function call.

Chapter 10CS 140Page 167 // This function fills an array with the contents of a user- // // specified input file, stopping at the end of the file or // // the capacity of the array, whichever comes first. // void inputList(int list[], int &listSize) { ifstream inputFile; char inputFileName[MAX_LIST_SIZE]; int value; cout << "Enter the name of the input file: "; cin >> inputFileName; inputFile.open(inputFileName); assert(!inputFile.fail()); listSize = 0; inputFile >> value; while ((!inputFile.eof()) && (listSize < MAX_LIST_SIZE)) { list[listSize] = value; listSize++; inputFile >> value; } inputFile.close(); return; } Notice that a character string is just another type of array. (We’ll see more details in the next chapter.) As long as there are more values in the input file AND more room in the array being filled, this loop keeps getting new entries for the array.

Chapter 10CS 140Page 168 // This function outputs the parameterized list, // // placing at most ten values on each output line. // void outputList(const int list[], int listSize) { int i; for (i = 0; i < listSize; i++) { cout << setw(3) << list[i]; if (i % 10 == 9) cout << endl; else cout << " "; } cout << endl; return; } // This function performs an "insertion sort" on the parameterized // // array, sorting its entries by assuming that the first k entries // // are already sorted, and then inserting the (k+1)-st entry where // // it belongs in that sorted k-sublist. // void sortList(int list[], int listSize) { int currentIndex; int backIndex; int currentValue; for (currentIndex = 1; currentIndex < listSize; currentIndex++) { currentValue = list[currentIndex]; backIndex = currentIndex - 1; while ((backIndex >= 0) && (list[backIndex] > currentValue)) { list[backIndex + 1] = list[backIndex]; backIndex--; } list[backIndex + 1] = currentValue; } return; } Essentially, this nested loop keeps “sliding” array entries over until it finds the slot where currentValue belongs. Since the sorted array is needed in the main function, no const modifier is employed in this function. Notice that the array elements may be used, but not altered in this function. This is because of the const modifier of the list parameter.

Chapter 10CS 140Page 169 // This function computes the arithmetic mean of the values in // // the parameterized array, returning this mean value to the // // calling function. Zero is returned if the array is empty. // double averageList(const int list[], int listSize) { int sum = 0; int i; if (listSize == 0) return 0; else { for (i = 0; i < listSize; i++) sum += list[i]; return double(sum)/listSize; } Contents of exam1.txt : Again, this function shouldn’t be altering the array’s contents, so a const modifier is used.

Chapter 10CS 140Page 170 // This function performs an "selection sort" on the parameterized // // array, sorting its entries by finding the smallest entry and // // swapping it with the first entry, then finding the next smallest // // entry and swapping it with the second entry, and so forth. // void sortList(int list[], int listSize) { int index; int currentIndex; int smallestIndex; int temp; for (currentIndex = 0; currentIndex < listSize - 1; currentIndex++) { smallestIndex = currentIndex; for (index = currentIndex + 1; index < listSize; index++) if (list[index] < list[smallestIndex]) smallestIndex = index; if (smallestIndex != currentIndex) { temp = list[currentIndex]; list[currentIndex] = list[smallestIndex]; list[smallestIndex] = temp; } return; } Essentially, this nested loop keeps finding the kth smallest entry and swapping it with what’s in array slot #(k-1). Notice that the function’s name and parameter list are identical with what was used in the previous example. The principles of information hiding are thus upheld, and this new sorting algorithm can replace the old one with no other changes to the program! An Alternative Sorting Algorithm Many sorting algorithms have been developed. In addition to the insertion sort we’ve already seen, there is a selection sort:

Chapter 10CS 140Page 171 // This function performs a sequential search of the parameterized // // array for the parameterized value. Starting at the top of the // // array, it examines each entry, returning a boolean value of true // // as soon as it finds the value, or a boolean value of false if it // // traverses the entire array without locating the value. // bool searchList(const int list[], int listSize, int soughtValue) { int i; for (i = 0; i < listSize; i++) if (list[i] == soughtValue) return true; return false; } Searching An Unsorted Array The most common algorithm for searching for a particular value within an unsorted array is the sequential search: Because the number of comparisons executed in this algorithm is, on average, directly proportional to the number of elements in the array, this algorithm is also known as a linear search.

Chapter 10CS 140Page 172 // This function performs a binary search of the parameterized // // array for the parameterized value. Starting at the middle // // of the array, it compares that entry to the sought value, // // returning a boolean value of true if they're equal, but // // eliminating the first half of the list from any further // // consideration if the middle value is too small or the second // // half if the middle value is too large. It continues halving // // the list until it actually finds the sought value, in which // // case it returns a boolean value of true, or until it // // eliminates the entire array from consideration, in which it // // returns a boolean value of false. // bool searchList(const int list[], int listSize, int soughtValue) { int lowIndex = 0; int highIndex = listSize -1; int middleIndex; while (lowIndex <= highIndex) { middleIndex = (lowIndex + highIndex) / 2; if (list[middleIndex] == soughtValue) return true; else if (list[middleIndex] < soughtValue) lowIndex = middleIndex + 1; else highIndex = middleIndex - 1; } return false; } Searching A Sorted Array The most common algorithm for searching for a particular value within a sorted array is the binary search. Notice that the number of comparisons executed in this algorithm is, on average, directly proportional to the base-2 logarithm of the number of elements in the array.

Chapter 10CS 140Page 173 Multidimensional Arrays It is possible to declare arrays of more than one dimension in C++. These arrays are essentially arrays of arrays... double hrsWorked[52][7]; 52 rows & 7 columns, for a total of 364 double values! int second[24][60][60]; 24 rows, 60 columns, & 60 layers for a total of integer values!

Chapter 10CS 140Page 174 A Simple Example #include using namespace std; void main() { int dozen[3][4] = {11,12,13,14,35,36,37,38,60,70,80,90}; int row; int col; for (row = 0; row < 3; row++) for (col = 0; col < 4; col++) { cout << dozen[row][col]; if (col != 3) cout << " | "; else if (row != 2) cout << endl << " | | | " << endl << " " << endl << " | | | " << endl; } cout << endl << endl; return; } The initialization of the two-dimensional array loads the array one row at a time.

Chapter 10CS 140Page 175 ////////////////////////////////////////////////////////// // This program reads data from an input file regarding // // a list of scheduled flights, and then outputs this // // data in a readable format to the monitor. // ////////////////////////////////////////////////////////// #include #include // We’ll see more about this in the next chapter! using namespace std; const int MAX_NBR_FLIGHTS = 10; enum CityCode { Atlanta = 1, Chicago, Dallas, Denver, LosAngeles, NewYork, Seattle }; void loadData(int flightData[][6], int &nbrOfRows); void computeTimes(const int data[][6], int time[], int nbrFlights); int timeChange(CityCode departCity, CityCode arriveCity); void outputChart(const int flyTable[][6], const int minutes[], int nbrRows); void outputFlightInfo(const int flightInfo[], const int minutes); void convertCodeToCity(CityCode city, char cityString[]); void computeTime(int time, int &hour, int &min, char AMorPM[]); double computePrice(int nbrMinutes, int nbrMiles); A Large Example: Flight Schedules The prototypes may neglect to specify at most one of the dimensions of a multidimensional array parameter. Otherwise, the compiler will be unable to distinguish the dimensions.

Chapter 10CS 140Page 176 // The main function coordinates the retrieval of the flight // // data, the calculation of each flight's time in the air, // // and the output of the flight info in a readable format. // void main() { int numberOfFlights; int flightData[MAX_NBR_FLIGHTS][6]; int elapsedTime[MAX_NBR_FLIGHTS]; loadData(flightData, numberOfFlights); computeTimes(flightData, elapsedTime, numberOfFlights); outputChart(flightData, elapsedTime, numberOfFlights); return; } // This function loads a two-dimensional array of integers // // with a prepackaged set of data about various flights. // void loadData(int flightData[][6], int &nbrOfRows) { ifstream flightFile; int flightNbr; nbrOfRows = 0; flightFile.open("flightData.txt"); flightFile >> flightNbr; while (!flightFile.eof()) { flightData[nbrOfRows][0] = flightNbr;// Flight Number flightFile >> flightData[nbrOfRows][1];// Source City Code flightFile >> flightData[nbrOfRows][2];// Destination City Code flightFile >> flightData[nbrOfRows][3];// Departure Time (Military) flightFile >> flightData[nbrOfRows][4];// Arrival Time (Military) flightFile >> flightData[nbrOfRows][5];// Distance In Miles nbrOfRows++; flightFile >> flightNbr; } return; } The main function “knows” that the flightData array has 10 rows and 6 columns. The loadData function “knows” that the array has 60 entries and 6 columns, so it “deduces” that there are 10 rows!

Chapter 10CS 140Page 177 // This function calculates the total amount of time, in minutes, // // between each flight's takeoff time and its arrival time. This // // data is stored in the parameterized array named time. // void computeTimes(const int data[][6], int time[], int nbrFlights) { int i, hours, minutes; for (i = 0; i < nbrFlights; i++) { hours = (data[i][4] / 100) - (data[i][3] / 100); if (hours < 0) hours += 24; hours += timeChange(CityCode(data[i][1]), CityCode(data[i][2])); minutes = (data[i][4] % 100) - (data[i][3] % 100); if (minutes < 0) { minutes += 60; hours--; } time[i] = 60 * hours + minutes; } return; } The integer data in columns 1 & 2 of that data array must be typecast to the enumerated CityCode type before being passed to the timeChange function.

Chapter 10CS 140Page 178 // This function uses a seven-city numerical code to determine the // // time difference between two cities, with positive numbers used // // for east-to-west flights, and negative numbers for west-to-east // // flights. Thus, for example, a NY-to-LA flight yields a result // // of 3, while an LA-to-NY flight yields a result of -3. // int timeChange(CityCode departCity, CityCode arriveCity) { int departTimeZone, arriveTimeZone; switch(departCity) { case(Atlanta): case(NewYork): {departTimeZone = 3; break;} case(Chicago): case(Dallas): {departTimeZone = 2; break;} case(Denver): {departTimeZone = 1; break;} case(LosAngeles): case(Seattle): {departTimeZone = 0; break;} } switch(arriveCity) { case(Atlanta): case(NewYork): {arriveTimeZone = 3; break;} case(Chicago): case(Dallas): {arriveTimeZone = 2; break;} case(Denver): {arriveTimeZone = 1; break;} case(LosAngeles): case(Seattle): {arriveTimeZone = 0; break;} } return (departTimeZone - arriveTimeZone); }

Chapter 10CS 140Page 179 // This function outputs the readable table of flight data to the monitor. // void outputChart(const int flyTable[][6], const int minutes[], int nbrRows) { int flight; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << " ICARUS AIRLINES FLIGHT SCHEDULE" << endl << endl << "Flight Departure Departure Arrival Arrival Ticket" << endl << "Number City Time City Time Price" << endl << " " << endl; for (flight = 0; flight < nbrRows; flight++) outputFlightInfo(flyTable[flight], minutes[flight]); cout << endl << endl; return; } The outputFlightInfo function is being sent a single row of the flyTable 2-D array, as well as a single entry of the minutes 1-D array!

Chapter 10CS 140Page 180 // This function outputs the flight information in the // // parameterized array, using the parameterized integer // // value to assist in computing the ticket price. // void outputFlightInfo(const int flightInfo[], const int minutes) { int hour; int min; char city[12]; char AMorPM[3]; double ticketPrice; cout << ' ' << flightInfo[0] << " "; convertCodeToCity(CityCode(flightInfo[1]), city); cout << city << setw(14-strlen(city)) << ' '; computeTime(flightInfo[3], hour, min, AMorPM); cout << setw(2) << hour << ':'; (min < 10) ? (cout << '0' << min) : (cout << min); cout << AMorPM; convertCodeToCity(CityCode(flightInfo[2]), city); cout << " " << city << setw(15-strlen(city)) << ' '; computeTime(flightInfo[4], hour, min, AMorPM); cout << setw(2) << hour << ':'; (min < 10) ? (cout << '0' << min) : (cout << min); cout << AMorPM; ticketPrice = computePrice(minutes, flightInfo[5]); cout << " $" << ticketPrice << endl; return; } This function is unaware of the fact that its first parameter is actually a row of a 2-D array, and that its second parameter is actually an entry in a 1-D array!

Chapter 10CS 140Page 181 // This function uses the numerical code associated with a particular // // city to yield the character string representing that city's name. // void convertCodeToCity(CityCode city, char cityString[]) { switch(city) { case(Atlanta) : {strcpy(cityString, "Atlanta"); break;} case(Chicago) : {strcpy(cityString, "Chicago"); break;} case(Dallas) : {strcpy(cityString, "Dallas"); break;} case(Denver) : {strcpy(cityString, "Denver"); break;} case(LosAngeles): {strcpy(cityString, "Los Angeles"); break;} case(NewYork) : {strcpy(cityString, "New York"); break;} case(Seattle) : {strcpy(cityString, "Seattle"); break;} } return; } // This function uses the military time represented in the parameter time // // to compute the civilian time in hours and minutes, as well as a string // // indicating whether that time is AM or PM. // void computeTime(int time, int &hour, int &min, char AMorPM[]) { (time < 1200) ? (strcpy(AMorPM, "AM")) : (strcpy(AMorPM, "PM")); hour = ((time/ ) % ); min = time % 100; return; }

Chapter 10CS 140Page 182 // This function computes the price of a flight, using $2.50 // // per minute or $0.25 per mile, whichever is more expensive. // double computePrice(int nbrMinutes, int nbrMiles) { double timePrice, distancePrice, price; timePrice = 2.50 * nbrMinutes; distancePrice = 0.25 * nbrMiles; price = (timePrice > distancePrice) ? (timePrice) : (distancePrice); return price; } Input file flightData.txt Resulting output

Chapter 11 Strings Goals: To introduce the idea of character strings as arrays To introduce the idea of character strings as arrays To demonstrate how character strings can be initialized To demonstrate how character strings can be initialized To illustrate how I/O works for character strings To illustrate how I/O works for character strings To explore the string-related functions in string.h To explore the string-related functions in string.h

Chapter 11CS 140Page 184 Character Arrays To facilitate processing strings of characters representing text, C++ includes several features that enable char arrays to be manipulated more easily for input, output, and initialization. To take advantage of these features, remember one rule: THE LAST MEANINGFUL CHARACTER IN THE ARRAY MUST BE FOLLOWED BY THE NULL CHARACTER, ‘\0’

Chapter 11CS 140Page 185 How Many Characters? The double-quotes around a constant character string hide the fact that each one actually ends with the null character. “Chicago” contains 8 characters “Reno\n\n” contains 7 characters “” contains 1 character

Chapter 11CS 140Page 186 Character String Variables Since the null character is required after the last meaningful character in a string, the character array that’s being used must be allocated one extra slot. char dayOfWeek[10]; “Wednesday” is the longest possible string, requiring ten characters, including the null character!

Chapter 11CS 140Page 187    Character String Variable Initialization As with any other array in C++, character array variables may only use the assignment operator (=) when they’re being initialized during variable declaration. char month[] = “June”; char month[] = {‘J’,‘u’,‘n’,‘e’,‘\0’}; char month[5] = “June”; char month[] = {‘J’,‘u’,‘n’,‘e’};  These are the same... …but this is different!

Chapter 11CS 140Page 188 Manipulating Individual Characters As with any other array in C++, individual array entries may be manipulated. Keep in mind that the null character (‘\0’) is used to signify where output should stop. #include using namespace std; void main() { char phrase[] = "To be\0or not\0to be."; cout << phrase << endl << endl; phrase[5] = '\n'; cout << phrase << endl << endl; phrase[12] = ' '; cout << phrase << endl << endl; return; } Notice how the original string ended with a null character that didn’t appear to exist in the initialization!

Chapter 11CS 140Page 189 #include using namespace std; void main() { char word[11]; strcpy(word,"BOOK"); cout << word << "!!!" << endl << endl; strcpy(word,"DICTIONARY"); cout << word << "!!!" << endl << endl; strcpy(word,"ENCYCLOPEDIABRITTANNICA"); cout << word << "!!!" << endl << endl; return; } String Functions In cstring A number of functions that facilitate the manipulation of character strings reside in the cstring library. Copies the sourceStringValue character string into the targetStringVariable (without checking to see if there’s enough room) strcpy( targetStringVariable, sourceStringValue )

Chapter 11CS 140Page 190 strcat( targetStringVariable, sourceStringValue ) #include using namespace std; void main() { char first[25] = "I do not like"; char second[] = " green eggs"; char third[] = " and ham!"; cout << first << endl << endl; strcat(first,second); cout << first << endl << endl; strcat(first,third); cout << first << endl << endl; return; } Concatenates the sourceStringValue character string onto the end of the targetStringVariable (without checking to see if there’s enough room)

Chapter 11CS 140Page 191 strlen( stringValue ) #include using namespace std; void main() { char simple[] = "Simon"; char hard[] = "Boiled\0Eggs"; char strange[] = "\0\0\0\0\0"; cout << "simple: " << simple << "\tLength = " << strlen(simple) << endl << endl; cout << "hard: " << hard << "\tLength = " << strlen(hard) << endl << endl; cout << "strange: " << strange << "\tLength = " << strlen(strange) << endl << endl; return; } Returns an integer equal to the length of stringVariable (stopping with the character just prior to the first null character)

Chapter 11CS 140Page 192 strcmp( firstStringValue, secondStringValue ) #include using namespace std; void main() { char allcaps[] = "YES"; char nocaps[] = "yes"; char firstcap[] = "Yes"; char earlier[] = "yen"; char later[] = "Yet"; cout << "Compare \"" << allcaps << "\" to: " << '\"' << allcaps << "\" (" << strcmp(allcaps,allcaps) << ")\t" << '\"' << nocaps << "\" (" << strcmp(allcaps,nocaps) << ")\t" << '\"' << firstcap << "\" (" << strcmp(allcaps,firstcap) << ")\t" << '\"' << earlier << "\" (" << strcmp(allcaps,earlier) << ")\t" << '\"' << later << "\" (" << strcmp(allcaps,later) << ")" << endl << endl;  Returns zero if the string values are equal, a negative integer if the first string value is “lexicographically” less than the second, and a positive integer if the second value is “lexicographically” less than the first Notice that upper-case letters are “lexicographically” less than lower-case letters.

Chapter 11CS 140Page 193 Problems With Character Arrays Numerous problems exist when we use traditional character arrays in C++: We can’t use assignment statements to give character arrays new values.We can’t use assignment statements to give character arrays new values. Resizing character arrays improperly might cause errors or unwanted side effects.Resizing character arrays improperly might cause errors or unwanted side effects. Retrieving specific parts of character arrays can be complicated.Retrieving specific parts of character arrays can be complicated. Inserting new characters into an existing character array can be tedious.Inserting new characters into an existing character array can be tedious. These problems and many more are resolved with the string class, made possible with a simple #include preprocessing statement!

Chapter 11CS 140Page 194 Using The C++ Standard string Class #include using namespace std; void main() { string firstName = "Fred"; string lastName = "Flintstone"; string fullName = firstName + ' ' + lastName; cout << fullName << endl << endl; fullName = "Wilma"; fullName += ' '; fullName += lastName; cout << fullName << endl << endl; fullName.replace(0, 5, "Ms."); cout << fullName << endl; fullName.replace(4, 10, "Rubble"); cout << fullName << endl; fullName.insert(4, "Betty "); cout << fullName << endl << endl; fullName[1] = 'r'; fullName.replace(5, 3, "arne"); cout << fullName << endl << endl; return; } Assignment statements, addition operators, output operators Additive assignment operators Member functions insert and replace Subscript operator

Chapter 11CS 140Page 195 Substrings and Size Adjustment with string s #include using namespace std; void main() { string name("Scooby Doo"); cout << name << endl << endl; string middle = name.substr(1,5); cout << middle << endl; middle.at(0) = name.at(7); cout << middle << endl; for (int i = 1; i <= 16; i++) { name.insert(7, middle + ' '); cout << name << endl; } cout << endl; return; } substr member function at member function string dynamically adjusts its size to accommodate new insertions!

Chapter 11CS 140Page 196 Lexicographical Ordering of string s #include using namespace std; void bubbleSort(string list[], int size); void main() { string quests[5] = {"jonny","Hadji","Race","bENTON","bandit"}; bubbleSort(quests, 5); for (int i = 0; i <= 4; i++) cout << quests[i] << endl; cout << endl; return; } void bubbleSort(string list[], int size) { bool swapped = true; int lastIndex = size - 1; string tempString; while ((swapped) && (lastIndex > 0)) { swapped = false; for (int i = 0; i < lastIndex; i++) { if (list[i] > list[i+1]) { tempString = list[i]; list[i] = list[i+1]; list[i+1] = tempString; swapped = true; } lastIndex--; }, =, ==, and != are all defined for class string, but they use a “lexicographical ” ordering! Arrays of type string are legal!

Chapter 11CS 140Page 197 #include using namespace std; int IbeforeEmistakes(string wd); int EbeforeImistakes(string wd); void main() { string word; int i; cout << "Enter a word (enter 'quit' to exit): "; cin >> word; while (word != "quit") { for (i = 1; i <= IbeforeEmistakes(word); i++) cout << "I BEFORE E EXCEPT AFTER C!" << endl; for (i = 1; i <= EbeforeImistakes(word); i++) cout << "E BEFORE I ONLY AFTER C!" << endl; cout << endl; cout << "Enter another word (enter" << " 'quit' to exit): "; cin >> word; } return; } int IbeforeEmistakes(string wd) { int mistakeCount = 0; int index = wd.find("ie"); while (index >= 0) { if ((index > 0) && (wd.find_first_of("Cc", index-1) == index-1)) mistakeCount++; index = wd.find("ie", index+2); } return mistakeCount; } Comparing Parts of string s string parameters can be passed by value! string values can be input! Finds the first index where any character in the parameterized substring occurs, starting at the parameterized position (returns -1 if none of the characters occur from the parameterized position on)! Finds the first index where the parameterized substring begins (returns -1 if it doesn’t occur)!

Chapter 11CS 140Page 198 Comparing Parts of string s (Continued) int EbeforeImistakes(string wd) { int mistakeCount = 0; int index = wd.find("ei"); while (index >= 0) { if (index == 0) mistakeCount++; else if ((index > 0) && (wd.find_first_of("Cc", index-1) != index-1)) mistakeCount++; index = wd.find("ei", index+2); } return mistakeCount; } Finds the first index where the parameterized substring begins starting at the parameterized position (returns -1 if it doesn’t occur from the parameterized position on)!

Chapter 11CS 140Page 199 Storage Allocation for a string #include using namespace std; void main() { string firstWord = "Chapter One: The Beginning"; string secondWord = "Page 1"; cout << firstWord.size() << ' ' << firstWord.length() << ' ' << firstWord.max_size() << ' ' << firstWord.capacity() << endl; cout << firstWord << ' ' << secondWord << endl << endl; firstWord.resize(11); cout << firstWord.size() << ' ' << firstWord.length() << ' ' << firstWord.max_size() << ' ' << firstWord.capacity() << endl; cout << firstWord << ' ' << secondWord << endl << endl; firstWord.resize(26,'*'); cout << firstWord.size() << ' ' << firstWord.length() << ' ' << firstWord.max_size() << ' ' << firstWord.capacity() << endl; cout << firstWord << ' ' << secondWord << endl << endl; firstWord.resize(41); cout << firstWord.size() << ' ' << firstWord.length() << ' ' << firstWord.max_size() << ' ' << firstWord.capacity() << endl; cout << firstWord << ' ' << secondWord << endl << endl; return; } length and size are identical max_size is the most the system can handle for one string ; capacity is the current memory devoted to the string in question