CSCI 2170 LAB 15
Enumerated Types, Typedef, Structs, and
Array of Structs


A few bookkeeping items before starting

1. All of the labs in this format should be done using one of the ranger systems (for example ranger2.cs.mtsu.edu).

2. You must click the "Create Answer Sheet for LAB #" for any lab of this format. Then place appropriate answers in the provided blanks.

3. Labs of this format will require you to submit the Answer Sheet (saved when completed as a PDF on your PC and then uploaded using the Gus Web Interface from your PC) as well several log files. See instructions at the very end of this writeup. Be sure to submit both sets of required items.


Objectives:
Review Enumerated types and Typedef
Learn to manipulate C++ structs
Provide practice in using arrays of structs
CREATE ANSWER SHEET for LAB 15

In this laboratory assignment we will consider the following:

A.  Review Enumerated Types and Typedef
B.  Using C++ Structures
C.  Array of Structs

A. Review of Enumerated Types and Typedef

The enum Statement

The enum (short for enumerated type) keyword can be used to define new data types.  In programming where advanced data structures will be required, the enum statement is essential.  The enum type should be used to provide good internal documentation.  This makes the program more readable and easier to understand (more self-documenting).  Also, another purpose for the enum statement is to help reduce logical errors in a program.

The enum statement provides a way to name integer constants and allows the programmer to invent a "new" type and to specify what values this new type can support.  The syntax of the enum appears as:


enum user-defined_type {listing of data values};

or

enum {listing of integer constants};

Note the following examples:


enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
enum Video {COMEDY, ADVENTURE, HORROR, MYSTERY, MUSICAL};
enum {FALSE, TRUE};

Now we have two new data types:  Day and Video.  Note that these are types, not variables!  Therefore, declarations similar to the following would be appropriate.

Day returnDay;
Video oneVideo;
The third enum statement listed above is equivalent to the following:
const int FALSE = 0;
const int TRUE = 1;

Enumerated variables are treated as "integers" by the compiler which means that these values are ordinal (ordered).  In the Day list of data items, MONDAY would be stored as 0 and THURSDAY would be stored as 3, for example.

There are disadvantages of using enumerated data types, however.  One major disadvantage is the fact that variables of this type cannot be input or output directly (using the input and output operators).  We will learn how to get around this later!

The typedef Statement

Another tool that is often used to aid in self documentation is the typedef statement.  The typedef declaration is used to create an alias for an existing data type and is invaluable in making a program easier to modify.  This will be extremely important to us later in the semester.

The syntax for the typedef follows:


typedef ExistingDataType NewDataType;
For example,

typedef char CharacterType;
aliases the type char as CharacterType.  Now we have a "new" type.  It is called CharacterType and we could declare variables as follows:

CharacterType letter;
CharacterType name[20];


NOTE: For each of the following exercises, indicate answers on the answer sheet.



Exercise 1:
a)  Show how to declare Real as a synonym for float (so that float and Real can be used interchangeably).

b)  Show how to declare the following constants using an enum statement:
WINTER =0, SPRING = 1, SUMMER = 2 and FALL = 3.




B. Using C++ Structures

In reviewing our previous knowledge of simple data types (aka scalar types), we remember that variables of these types have a major restriction:  these variables may only store one data item.  For example, if the following declaration is made:


int oneNumber;
oneNumber may only store one integer value.  To store multiple data items of the same type, we have the array structured data type.  For example,

const unsigned int MAX_VALUES = 50;
int manyNumbers[MAX_VALUES];


will set up an array called manyNumbers that will have the ability to store as many as 50 integers.  One major disadvantage of the simple data type and the array structure is the fact that each type only stores one data type.  For example, the manyNumbers array can store only integers and the oneNumber variable may store only an integer.  There are many applications where it would be beneficial to have one variable that could store several types of information at the same time.  For example, in a program to manage inventory and customers for a video store, it would be nice to have:

C++ provides the structure data type to satisfy this need.  The C++ struct is a group of data items that do not necessarily have the same data type. The struct should be used whenever the programmer wishes to store related information into one variable name. 

Declaring Structs

The syntax for the C++ struct type follows:

struct  StructName
{
     list of member types and member names;
};

Exercise 2: Copy the files cla15.cpp, cla15.dat  and cla15b.dat that are found in the $CLA directory to your account.  cla15.cpp is a short program that reads data from the data files, cla15.dat and cla15b.dat,  and prints out information related to videos owned by the Movie Rent Video Store.  This program displays a menu so that the user can select one of the following options:
1) Print a list of all videos owned by the Movie Rent Video Store
2) Print a list of all customers
3) Print out a list of rental information by video titles
0) Exit this program

Presently, this program reads inventory information from a file called cla15.dat that contains the following information for each video owned by the company:  name of video, the number of copies of a particular title, and the video type (mystery, comedy, etc.).  The program, as it is given, will allow the user to choose option 1) or option 0) only. We will be adding code to this file so that the other options are eventually added to the code. Compile and execute this program to make sure that you understand what the program is doing.

In examining our cla15.dat file, we realize that we need a struct that will store the following information for each video: name of the video, the number of copies of the video owned by the video store and the type of video.  The variable, videoInfo, to declare a video struct of this type follows:



struct Video
{
     string movieTitle;            //name of movie
     unsigned int numberCopies;    //number of copies
     string videoType;             //type of video
};
Video videoInfo;


NOTE that Video is a TYPE not a variable!!!  Thus, we must declare a variable to be of type video for memory locations to be associated with the member elements.  Also, note that videoInfo is a variable that has been declared to be of type Video!!

The items included in the C++ struct are called members of the struct and we will learn later that structs can have data members (as shown above) and/or function members.

As stated earlier, we need to add code to the  cla15.cpp program so that it will also evaluate customers and print out a list of video customer information.  Let's now examine the cla15b.dat file.  This file contains customer information for the video store.  All data in this file is in the following form for each customer:
 

name of customer (a string)
id number of customer (integer)
name of video rented by the customer (a string)
return date of the video (a string)


Exercise 3: Using the above struct declaration as a guide, show code to set up a struct called customerType that will have fields for a customer's name, the customer's id number (integer),  the title of the movie/video rented, and when the video is to be returned.  Also declare a variable customer of the type customerType. Insert this code into the two positions indicated by comments in the cla15.cpp program.

Manipulating C++ Structs

The dot operator, "." , is used when accessing structs. It is preceded by the struct variable name and is followed by the name of a member of that struct.  Hence, the "." operator is often called a membership operator.  The following code will read from the stream videoIn and print values for the variable videoInfo as declared above.

//get the video information
getline(videoIn, videoInfo.movieTitle);
videoIn >> videoInfo.numberCopies;
videoIn.get(endOfLine);
getline(videoIn, videoInfo.videoType);

//print out video information
cout << "\n\nName of video:\t\t" 
     << videoInfo.movieTitle << endl;
cout << "Number of copies:\t" 
     << videoInfo.numberCopies << endl;
cout << "Video type:\t\t"
     << videoInfo.videoType << endl;


Exercise 4: Add code to read values for the variable customer described in exercise 3.  This is accomplished by a call to the function getCustomer().  Complete the function getCustomer() so that it will read values for one customer from the indicated input file stream.  Include this code in the indicated position of the cla15.cpp program.
Other manipulations that might occur using structs will be addressed by example.

How are structs passed to functions?

This question might best be answered by showing the complete program to process one video.


#include <fstream>
using namespace std;

//set up global struct type
struct Video
{
     string movieTitle;          //name of movie
     unsigned int numberCopies;  //number copies owned
     string videoType;           //type of video
};

//function prototyes
void getVideo(Video&, ifstream&);   //get one video

int main()
{
     //variable declarations
     Video videoInfo;             //one video

     //declare and open the file containing 
     //video information
     ifstream videoIn;
     videoIn.open("cla15.dat");

     //read from the file until eof is reached
     getVideo(videoInfo, videoIn); 
     while (videoIn)
         getVideo(videoInfo, videoIn);

     return 0;
} //end of main

//Function to get one movie's information
void getVideo (Video& oneVideo,        
               ifstream & videoIn)     
{
     char endOfLine;

     //get the video information
     getline(videoIn, oneVideo.movieTitle);
     videoIn >> oneVideo.numberCopies;
     videoIn.get(endOfLine);
     getline(videoIn, oneVideo.videoType);
}

Can assignment statements be used between two struct variables of the same type?

YES!!!  Note the following function that swaps two structs of type Video.


void swap (Video& one, Video& two)
{
     Video temp;
     temp = one;
     one = two;
     two = temp;
}

C. Array of structs

A more common application of structs occurs when multiple structs of the same type are needed in a program.  Suppose that we need to write a program that performs manipulations on as many as 100 videos.  The data structure that would be needed for this application is an array of structs.

Defining an Array of Videos

Remember that when working with structs, one of the first things that is accomplished is the creation of a struct type.   This type is used to declare an array of this new type.  For example, the following code defines a variable called allVideos that will store information for as many as 100 videos.


const unsigned int MAX_VIDEOS = 100;
Video allVideos[MAX_VIDEOS];

Exercise 5 Add code to the cla15.cpp program to define a variable called allCustomers that will store information contained in the cla15b.dat file for as many as 20 customers as described in Exercise 4.

Manipulation of Arrays of Structs

Data included in an array of structs is accessed by denoting the following in the order specified:

1) indicate array variable name
2) indicate which struct to be accessed (show the subscript)
3) indicate which member of the struct that is to be accessed.

For example, the following:


cout << allVideos[0].movieTitle << endl;

will print out the movie title of the first video included in the list of rental videos.
 
Exercise 6: Write code to print out the id number of the second customer included in the allCustomers array as described in exercise 5.  Place your answer on the answer sheet.

Passing an Array of Structs to a Function

Suppose that we need a function called findAndPrint that will search the allVideos array for a particular type of video and will print out all videos included in the list that have this type.  The function should receive the allVideos array so that it can be searched and secondly, the function should receive the type of videos that it is searching for.  The function header definition will appear as:

void findAndPrint (Video shows[], string showType)
and we can call this function using the following statement:
findAndPrint(allVideos, "comedy");


Exercise 7: Add code to the stub function called printRentalInfo (at the indicated position inside cla15.cpp) so that it will receive the allCustomers array defined in Exercise 5, a movie title, and the number of customers, and will print out a list of all the names of customers who have rented the video indicated in the movie title sent to the function. 

Exercise 8: Now complete the Movie Rent Video Store program.  Add code to the stub function called printCustomer (at the indicated position inside cla15.cpp) that will receive one struct of type customerType and will print out all information related to this customer (name, id, name of video rented, and return date of video).

Exercise 9:   Modify (mostly be "enabling" some code that is currently commented-out) the program so that all menu selections can be selected by the user.   Compile and execute this program demonstrating that all options in the menu are now operational.

You are to submit the source program listing of the modified code, compilation results, and a sample run of the program. Something like the following UNIX commands will let you create what is required:

       $ script lab15ex9.log
       $ pr -n -t -e4 cla15.cpp
       $ c++ cla15.cpp -o cla15
       $ cla15
       $ exit
(Be sure to properly exit the script session!)

----- End of Lab 15 - C++ Enumerated Types, Typedefs, Structs, and Array of Structs -----
Complete the Exercises on the Answer Sheet


 
 
 
Return to the top of this lab