Chapter 9 Text Files User Defined Data Types User Defined Header Files



Similar documents
What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

7.7 Case Study: Calculating Depreciation

Appendix K Introduction to Microsoft Visual C++ 6.0

Basics of I/O Streams and File I/O

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

C++ Input/Output: Streams

Chapter 7. Functions 7-1

Formatting Numbers with C++ Output Streams

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Member Functions of the istream Class

Comp151. Definitions & Declarations

Chapter One Introduction to Programming

Moving from C++ to VBA

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Sequential Program Execution

While Loop. 6. Iteration

The Payroll Program. Payroll

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Answers to Review Questions Chapter 7

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Lecture 2 Notes: Flow of Control

Illustration 1: Diagram of program function and data flow

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Chapter 8 Selection 8-1

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Data Structures using OOP C++ Lecture 1

6. Control Structures

Visual Studio 2008 Express Editions

Passing 1D arrays to functions.

Appendix M: Introduction to Microsoft Visual C Express Edition

Ubuntu. Ubuntu. C++ Overview. Ubuntu. History of C++ Major Features of C++

Using C++ File Streams

Common Beginner C++ Programming Mistakes

C++FA 5.1 PRACTICE MID-TERM EXAM

An Incomplete C++ Primer. University of Wyoming MA 5310

C++ INTERVIEW QUESTIONS

Conditions & Boolean Expressions

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

C++ program structure Variable Declarations

Computer Programming C++ Classes and Objects 15 th Lecture

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Compiler Construction

C++ Language Tutorial

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Sources: On the Web: Slides will be available on:

CS 101 Computer Programming and Utilization

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

5 Arrays and Pointers

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

A brief introduction to C++ and Interfacing with Excel

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

13 Classes & Objects with Constructors/Destructors

Creating a Simple Visual C++ Program

if and if-else: Part 1

Answers to Selected Exercises

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

CSI33 Data Structures

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

EP241 Computer Programming

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Syllabus OBJECT ORIENTED PROGRAMMING C++

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Introduction to Java

COMPUTER SCIENCE 1999 (Delhi Board)

Repetition Using the End of File Condition

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Chapter 5. Selection 5-1

arrays C Programming Language - Arrays

The While Loop. Objectives. Textbook. WHILE Loops

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Ch 7-1. Object-Oriented Programming and Classes

UEE1302 (1102) F10 Introduction to Computers and Programming

Chapter 3: Writing C# Expressions

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Arrays in Java. Working with Arrays

C++FA 3.1 OPTIMIZING C++

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

J a v a Quiz (Unit 3, Test 0 Practice)

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University


Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Subject Name: Object Oriented Programming in C++ Subject Code:

How to: Use Basic C++, Syntax and Operators

Transcription:

Chapter 9 Text Files User Defined Data Types User Defined Header Files 9-1

Using Text Files in Your C++ Programs 1. A text file is a file containing data you wish to use in your program. A text file does not contain any C++ declarations or statements just the data. Enter the CodeWarrior editor and create your text file. Save your file with a.dat file extension. It will make things easier if your file has any string data on a line by itself. Numeric data is easily read when you have several items per line as white space is used to delimit the various data items. 2. To use the file in your program you need to include the fstream header file in your program #include<fstream> 3. The function used to read from the file requires a local variable to represent your actual file on disk ifstream infile You may choose any name you like (I typically use infile for files I am reading from and outfile for files I am writing to). 4. You must open the file for reading with the open statement using the variable you declared and the actual file on disk infile.open( people.dat ) is the statement used to associate the variable in your program (infile) with an actual file on disk (people.dat). From now on in your program when the variable name infile is used the program will look at the file on disk specified in the open statement. The open statement also sets the file pointer to the top of the file. 5. To read from the file instead of the keyboard, replace the cin variable with the variable you declared in your program. Examples: getline(infile,name[i]) infile>>age[i] etc. 6. Always close the file before you exit the function that opened it. infile.close 7. STUDY THE FOLLOWING PROGRAMS CAREFULLY AND YOU SHOULD HAVE NO PROBLEMS USING TEXT FILES IN YOUR PROGRAMS. 9-2

// This program demonstrates the loading of an array when the number of // data items is known #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; void LoadArrays(string nm[], int ag[]); void OutputArrays(string nm[], int ag[]); void main(void) string names[5]; int ages[5]; // array of 5 names - READ from file // array of 5 ages - READ from file // call functions to read info and print contents of the arrays LoadArrays(names, ages); OutputArrays(names, ages); void LoadArrays(string nm[], // array for names - OUT int ag[]) // array of ages - OUT ifstream infile; // declared locally as no other fns need the file // open the file - infile.open("people.dat"); for(int i=0; i < 5; ++i) getline(infile,nm[i]); infile >> ag[i]; infile.ignore(100,'\n'); // close the file infile.close; void OutputArrays(string nm[], // array of names - IN int ag[]) // array of ages - IN for(int i=0; i < 5; ++i) // note use of length function to format output cout << endl << nm[i] << setw(25- nm[i].length( )) << ag[i]; 9-3

// This program reads an unknown number of elements from a file #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; void LoadArrays(string nm[], int ag[], int& ct); void OutputArrays(string nm[], int ag[], int ct); void main(void) string names[25]; int ages[25]; int counter; // array holds up to 25 names - READ from file // array holds up to 25 ages - READ from file // counts array elements as the are read - CALC // initialize counter to count people as they are read from the file counter = -1; // Call functions to load and output the arrays LoadArrays(names, ages, counter); cout << "There are " << counter+1 << " names & ages in the file\n\n"; OutputArrays(names, ages, counter); void LoadArrays(string nm[], // array of names - OUT int ag[], // array of ages - OUT int& ct) // array location counter - INOUT ifstream infile; // file variable for input file // open the file infile.open("people.dat"); while(!infile.eof()) // increment the counter each time the loop is entered ++ct; // note that the name of the file variable replaces cin getline(infile,nm[ct]); infile >> ag[ct]; // "flush" the buffer infile.ignore(1,'\n'); // close the file infile.close; void OutputArrays(string nm[], // array of names - IN int ag[], // array of ages - IN int ct) // number of items in arrays - IN for(int i=0; i <= ct; ++i) // note the use of the length function to format the output cout << endl << nm[i] << setw(25- nm[i].length( )) << ag[i]; 9-4

Following is the datafile, people.dat, used in the previous programs. Sam Jones 55 Susie Jones 12 Sally Jones 50 Josh Jones 15 Adam Jones 78 9-5

The typedef Statement The typedef statement is used not to create a new type but instead to give a new name to an existing type. The data type bool is relatively new. Prior to the introduction of the bool type we could define our own type to add readability to a program. typedef int Boolean; const int TRUE = 1; const int FALSE = 0; Boolean loopflag; // a variable that may contain TRUE or FALSE Although loopflag actually contains an integer value, the program is made more clear by using the named constants TRUE and FALSE. Array data type example: typedef float FloatArrayType[100]; // anything of type FloatArrayType is defined // as a 100 element array of float values FloatArrayType myarray; // myarray is a variable representing a 100 element // array of float values Because the compiler knows the size and type of the array from the definition of the type FloatArrayType, we can now use this type in a formal parameter list. void LoadArray(FloatArrayType anarray); The typedef statement allows us to create code that is more self documenting and easier to understand. 9-6

Modified 2-dimensional array program using the typedef statement #include <fstream.h> #include <iomanip.h> const int NUMOFROWS = 4; const int NUMOFCOLS = 5; // declaration of a two-dimensional array data type typedef float SalesArrayType[NUMOFROWS][NUMOFCOLS]; void LoadSalesData(SalesArrayType sale); void PrintSalesData(SalesArrayType sale); void CalcWeeklySales(SalesArrayType sale); void main(void) SalesArrayType sales; // call function to load the arrays with the month's sales LoadSalesData(sales); // call function to output monthly sales table PrintSalesData(sales); // call function to sum and output weekly sales total CalcWeeklySales(sales); void LoadSalesData(SalesArrayType sale) ifstream infile; // open the file infile.open("sales.dat"); // load the array for(int i = 0; i < NUMOFROWS; i++) for(int j = 0; j < NUMOFCOLS; j++) infile >> sale[i][j]; infile.close; void PrintSalesData(SalesArrayType sale) // output headings cout << setw(45) << "Monthly Sales\n\n"; cout << "\t\t\tmonday Tuesday Wednesday Thursday Friday\n\n"; // print the array for(int i = 0; i < NUMOFROWS; i++) cout << "Week " << i+1; 9-7

for(int j = 0; j < NUMOFCOLS; j++) cout << setw(12) << sale[i][j]; cout << endl; void CalcWeeklySales(SalesArrayType sale for(int i = 0; i < NUMOFROWS; i++) float sum; sum = 0.0; for(int j = 0; j < NUMOFCOLS; j++) sum = sum + sale[i][j]; cout << "\n\nsales for week " << i+1 << " = " << sum; 9-8

Enumeration Types Enumeration types are used primarily to add readability to a program and make it more self documenting. Example: enum Dogs POODLE, COLLIE, LABRADOR, GOLDEN_RETRIEVER; We have created a new type called Dogs and listed the elements (possible values) inside the braces. We can now declare variables of this type. Dogs mydog; Dogs yourdog; mydog = GOLDEN_RETRIEVER; yourdog = POODLE; yourdog = mydog; yourdog = COLLIE ; // invalid Each element has a numeric value associated with it, that is to say they are ordered. The value of POODLE is 0, the value of COLLIE is 1, etc. This allows us to use the relational operators when working with enumeration types. While each element has an int value associated with it, you may not work with this type as though it was an int. Suppose I wanted to have the value of mydog become the next value in the list. mydog = mydog + 1; mydog++; // invalid // invalid We need to use type casting mydog = Dogs(myDog + 1); // valid 9-9

Enumeration types may be used in switch statements and as the loop control variable in a for loop. For(Dogs mydog = POODLE; mydog <= GOLDEN_RETRIEVER; mydog = Dogs(myDog+1)) It is not possible to input or output an enumeration type directly. To output the value of the members of type Dogs a switch statement is necessary. switch(mydog) case POODLE case COLLIE case LABRADOR case GOLDEN_RETRIEVER : cout << Poodle ; : cout << Collie ; : cout << Labrador ; : cout << Golden Retriever ; 9-10

User Defined Header Files We have been using the #include pre-processor directive in our programs to gain access to routines supplied by the C++ standard libraries. It is also possible for us to create our own files of declarations and functions that may be written and compiled once and accessed by any program via the #include directive. Suppose I want to declare an enumeration type called Days and make this type available to any program that wishes to use it. Additionally, I would like to declare a data type for an array used to hold sales figures for the week. The declarations will be stored in a file called myheader.h. Any program wishing to access these declarations may do so by using the following directive #include myheader.h Note the use of the quotation marks. The directive #include <iostream.h> indicates that the header file will be found in the directory with the standard C++ libraries where the directive #include myheader.h indicates that the header file is located in the current directory (in our case, the current project folder). 9-11

// User defined header file demonstration #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales); // Function to output the weekly sales void OutputSales(SalesArrayType sales); void main(void) // declaration of array variable using type defined in myheader.h SalesArrayType salesarray; cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); LoadSales(salesArray); OutputSales(salesArray); // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; 9-12

// Function to output the weekly sales void OutputSales(SalesArrayType sales) cout << "\n\nsales for the Week\n"; cout << "--------------------\n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON: cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-13

// file myheader.h // user defined header file to specify two user defined data types // enumeration type for days of the week enum Days SUN, MON, TUE, WED, THU, FRI, SAT; // typedef for a one-dimensional array typedef float SalesArrayType[7]; It is also possible to create header files that contain more than declarations. In the following example there are three files used. 1. A program file containing the main function. 2. A header file (myheader.h) containing the enum and typedef statements as well as two function prototypes. 3. A program file (myheader.cpp) containing the code for the functions specified in myheader.h. The actual implementation of the functions is kept separate from the header file where the prototypes appear. Anyone wishing to use the data types and functions provided need only see the declaration of the types and the function prototypes. There is no need for the user to have access to the actual implementation. 9-14

// This file contains the main function #include "myheader.h" // file is located in the project folder void main(void) // declaration of array variable using type defined in myheader.h SalesArrayType salesarray; // Calls to functions prototypes contained in myheader.h and // implementation contained in myheader.cpp LoadSales(salesArray); OutputSales(salesArray); 9-15

// file myheader.h // user defined header file to specify two user defined data types // and the prototypes for two functions to act on the array // enumeration type for days of the week enum Days SUN, MON, TUE, WED, THU, FRI, SAT; // typedef for a one-dimensional array typedef float SalesArrayType[7]; // Function to load the weekly sales void LoadSales(SalesArrayType sales); // Function to output the weekly sales void OutputSales(SalesArrayType sales); 9-16

// File myheader.cpp contains the implementation portion of myheader.h #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; // Function to output the weekly sales void OutputSales(SalesArrayType sales) cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); cout << "\n\nsales for the Week\n"; cout << "--------------------\n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON : cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-17

// File myheader.cpp contains the implementation portion of myheader.h // user defined header file demonstration #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include "myheader.h" // file is located in the project folder // Function to load the weekly sales void LoadSales(SalesArrayType sales) ifstream infile; infile.open("sales.dat"); for (Days index = SUN; index <= SAT; index = Days(index + 1)) infile >> sales[index]; infile.close; // Function to output the weekly sales void OutputSales(SalesArrayType sales) cout << "\n\nsales for the Week\n"; cout << "--------------------\n"; for (Days index = SUN; index <= SAT; index = Days(index + 1)) // recall that enum types may not be output directly switch (index) case SUN : cout << "\nsunday: "; case MON : cout << "\nmonday: "; case TUE : cout << "\ntuesday: "; case WED : cout << "\nwednesday: "; case THU : cout << "\nthursday: "; case FRI : cout << "\nfriday: "; case SAT : cout << "\nsaturday: "; cout << setw(8) << setprecision(2) << sales[index] << endl; 9-18

Notes on User Defined Header Files 1. Make certain all related files are in the project folder. 2. You may have only one.cpp file that contains a main function listed in the Sources section of the project. 3. The name of the.cpp file containing the implementation of the functions listed in the header file must be listed under the Sources section of the project. Use the Add Files option from the Project menu to add this file to the list of sources. You may eventually have several files active under Sources but remember that ONLY ONE may contain a main function. 9-19

Name Due Date Header Files Assignment 1. Create a header file that contains the following: - a typedef to define a one dimensional array of 10 integers - the prototype for a function to load the array from a datafile - the prototype for a function to calculate the sum of the elements in the array - the prototype for a function to output the contents of the array 2. Create the necessary.cpp file that contains the code for the functions listed in #1. 3. Create a file that contains the main function. The file will do the following: - call the load function - assign to a variable called thesum the return value from the function that sums the array - call the output function - output the value of thesum 9-20