[CS200.U06.EX] Exercise: Functions

CS 200: Concepts of Programming with C++, Summer 2022

🔙 BACK TO UNIT PAGE | CANVAS TURN IN


📝 Assignment

Exercises are meant to be solo effort, please try to complete it on your own. You can ask the instructor or a tutor questions if you get really stuck, but all the information you need to complete the assignment is in here, or in the related reading/lectures.

If you get stuck, please post questions in the Unit 6 'Help!' discussion board.

🔧 Setup

FIRST, from your "My Repls" page on Repl.it create a New folder for this weeks' assignments name it Unit06. Within this folder you will create separate Repl projects for each program. When you turn in the assignments, you will copy the URL to your folder as the submission.

🎁 Submitting your work

First, make sure all your programs are inside your Unit06 folder. If they're not you can click on the three dots on the right side of the program name and click "Move".

PLEASE GIVE YOUR PROGRAMS THE FOLLOWING NAMES:

  • Unit 06 Program 1 Program Loop
  • Unit 06 Program 2 Array Utilities
  • Unit 06 Program 3 Math Functions
  • Unit 06 Program 4 Character Data

Clean code also means the ability to find the code itself, so if your project is unkempt and hard to navigate you will lose points.

To submit your work, navigate to the folder for your exercises on replit. Copy the URL to that directory (e.g., https://replit.com/@rsingh13?path=folder/Unit06) and paste it in here in Canvas.

Once you've turned in the assignment, make sure to also post your program in the code review assignment, [CS200.U06.PR] 🔎 Functions - Peer review

💻 Programs

Quick jump: Program 1: Basic program loop | Program 2: Array utilities | Program 3: Math functions | Program 4: Character data |

Program 1: Basic program loop

Let's look at how to create a basic program loop that will keep running until the user decides to exit. We will use a while loop to make sure the program doesn't end until the user hits the "exit" option.

EXAMPLE PROGRAM
------------------------------
MAIN MENU
1. Show favorite movie
2. Show favorite game
3. Quit

1

Favorite movie is The Lost Skeleton of Cadavra!


------------------------------
MAIN MENU
1. Show favorite movie
2. Show favorite game
3. Quit

2

Favorite game is Dragon Quest Builders 2!


------------------------------
MAIN MENU
1. Show favorite movie
2. Show favorite game
3. Quit

3

GOODBYE!

Forking the starter code

Start by going to https://replit.com/@rsingh13/Unit-06-Program-1-Program-Loop#main.cpp and making a fork of the program!

Modifying the program

The code in main.cpp is basically done, but make sure to read over it. This file uses a while loop to keep the program running, and only sets done = true when the user selects option 3.

functions.h contains the function declarations for this program, so this part is also done.

functions.cpp is where you'll be workingm where there are // TODO: comments.

void DisplayMenu()

This function is just responsible for displaying the main menu to the screen. The main menu should have 3 options, numbered 1 , 2, and 3. #3 should be the EXIT option, and you can give 1 and 2 any label you want - something simple that you will implement later, like "display favorite movie" or "add two numbers".

int GetChoice( int min, int max )

This function will get input from the user, but the error checking isn't implemented yet. We need to make sure that their selection is between the min and max values before the return statement.

The choice value is invalid while:

  1. choice is less than the min, OR
  2. choice is greater than the max

Use a while loop with the condition detailed just above. If you detect an invalid input (the while loop starts), then display an error message and write another cin statement so they have a chance to enter a new value.

void DoSomething1()

Implement something simple in this function, such as displaying your favorite movie to the screen with a cout statement.

void DoSomething2()

Implement another something simple within this function.

Program 2: Array utilities

⭐⭐⭐

For this project we're going to create a set of functions to help us work with our arrays more easily.

~/Project$ ./main
            0:  4.99
1:  5.99
2:  7.75
3:  3.12
4:  4.54
5:  6.54
6:  7.89
7:  10.00
8:  12.50
9:  14.20
            

Setting up the project

Create the following files:

  • main.cpp
  • ArrayTools.h
  • ArrayTools.cpp
  • item_prices.txt

You can paste the following information into your item_prices file:

4.99
5.99
7.75
3.12
4.54
6.54
7.89
10.00
12.50
14.20

This program will expect to receive 1 argument, which will be an input file, such as item_prices.txt.

Within main(), go ahead and create an array of floats of size 10.

ArrayTools.h

Declarations for four functions will be needed:

Function name

LoadData

Inputs

  1. float arr[]
  2. int size
  3. ifstream& input

Returns

nothing (void)
void LoadData( float array[], int size, ifstream input );

Function name

DisplayData

Inputs

  1. float arr[]
  2. int size

Returns

nothing (void)

Make sure to use #include statements for any special data types used in here (hint: fstream), and also don't forget to add your file guards into this file!

ArrayTools.cpp

Within this file we are going to define our functions. Make sure to #include the ArrayTools.h file, as well as iostream and fstream.

Copy your declarations from the .h file and paste them into here, removing the ending ; and adding a code block { }.

Function name

LoadData

Inputs

  1. float arr[]
  2. int size
  3. ifstream& input

Returns

nothing (void)

The ifstream object is passed into the function, so a file is already loaded. This function will read in the entire file, inserting each item into the array (which is also a parameter.) We also have the array size, which is another parameter.

Create a for loop to iterate over all the indices of the array (from 0 to the size, not including size). Within this loop read in one item from the input into the array at the current index. Use the input stream operator.

At the end you don't need to return the array, because arrays are automatically passed directly to functions.

Function name

DisplayData

Inputs

  1. float arr[]
  2. int size

Returns

nothing (void)

This function is responsible for displaying all the elements of the array. The array and the array's size are passed in as parameters.

Create a for loop that iterates over all the array indices, displaying the index of each element and the value of each element in the array.

main.cpp

Back in main, the first argument of the argumentList should be the filename:

string filename = argumentList[1];

If the input file fails to load, then display an error message and exit the program:

ifstream input( filename );
if ( input.fail() )
{
    cout << "ERROR: Failed to read " << filename << endl;
    return 2;
}

Remember that you need to declare a float array of size 10 to store the prices.

Otherwise, call the LoadData function, passing in the input file, the array, and the array's size. Let's say your array name is priceArray and your ifstream object is named input. Calling it will look like this:

LoadData( priceArray, 10, input );

Afterwards, also call the DisplayData function, passing in the appropriate data.

If you get build errors, make sure you have the appropriate #includes in your main.cpp file.

Once run, the program should look like this:

0:  4.99
1:  5.99
2:  7.75
3:  3.12
4:  4.54
5:  6.54
6:  7.89
7:  10.00
8:  12.50
9:  14.20

Program 3: Math functions

⭐⭐

For this function we will work with short functions that take some inputs and return some output. These are meant to be like math functions, where it calculates something based on a formula.
We will be calling our functions in several ways, and also writing simple unit tests to automate testing.

$ ./main sum
Operation 1: Sum( 2, 3 )
5
Operation 2: num1 = 5, num2 = 7, Sum( num1, num2 )
12
Operation 3: num1 = 2, num2 = 7, result = Sum( num1, num2 )
9            

1. Creating the program

Create a new replit project. We will need the following source files:

  • main.cpp
  • Math.h
  • Math.cpp
  • MathTester.h
  • MathTester.cpp

The program will take in one argument, the function to be ran. You can use the following as the expected forms text:

cout << "Expected forms:" << endl;
cout << "(1) " << argumentList[0] << " sum" << endl;
cout << "(2) " << argumentList[0] << " area" << endl;
cout << "(3) " << argumentList[0] << " slope" << endl;
cout << "(4) " << argumentList[0] << " tests" << endl;

Create a string variable named functionToRun and assign it the value of argument [1]. We will implement each function one at a time.

Within the .h files, make sure to have your FILE GUARDS. Each .h file should have unique labels (e.g., don't use "_MATH_H" in both places.)

#ifndef _MATH_H
#define _MATH_H

// code goes here

#endif

The Math.cpp file should have #include "Math.h" up top, the MathTester.cpp file should have #include "Math.h" and #include "MathTester.h" up top, and the main.cpp file should also include both Math.h and MathTester.h.

2. The Sum function

Function declaration

Within Math.h we need to write the function declaration for the Sum function.

The Sum function will take in two input parameters:

  1. number1, a float
  2. number2, a float

The function will add these two numbers together and return the result, so its return type is also a float.

The declaration will look like this:

float Sum( float number1, float number2 );
Function definition

Copy the function declaration from the .h file and paste it in here. Remove the semicolon ; at the end of the line and add a code block { }, giving us an empty function definition:

float Sum( float number1, float number2 )
{
  
}

This function needs to use the return keyword to return the result of number1 + number2, so it will look like this:

float Sum( float number1, float number2 )
{
    return number1 + number2;
}
Calling the function

Within main(), add an if statement. If functionToRun is equal to "sum", then we're going to call the Sum function in a few different ways.

if ( functionToRun == "sum" )
{
    cout << "Operation 1: Sum( 2, 3 )" << endl;
    cout << Sum( 2, 3 ) << endl;

    cout << "Operation 2: num1 = 5, num2 = 7, Sum( num1, num2 )" << endl;
    float num1 = 5;
    float num2 = 7;
    cout << Sum( num1, num2 ) << endl;

    cout << "Operation 3: num1 = 2, num2 = 7, result = Sum( num1, num2 )" << endl;
    num1 = 2;
    num2 = 7;
    float result = Sum( num1, num2 );
    cout << result << endl;
}

The first operation we call Sum with two integer literals: 2 and 3. The function is also in a cout statement, so whatever its result is will be displayed to the screen.

The second operation uses two variables to pass into the Sum function as arguments. Sum's result is also being output to the screen here.

The third operation uses variables for the arguments, and stores the return value in a third float result function. Whenever a function returns data, you must store it somewhere or cout it immediately. If you just call the function like this...

Sum( num1, num2 );

... The math happens, but we're not storing the result anywhere, so we have no way to access that information. We MUST assign a variable to the result of the function.

Running the program

To test what we have so far, build the program and run it with sum as the argument:

./main sum

The output should look like this:

$ ./main sum
Operation 1: Sum( 2, 3 )
5
Operation 2: num1 = 5, num2 = 7, Sum( num1, num2 )
12
Operation 3: num1 = 2, num2 = 7, result = Sum( num1, num2 )
9
Creating a unit test

Next we're going to create a unit test for the Sum function so we don't have to manually test it out. We can write unit tests easily for functions that have inputs and outputs, and don't include any cin or cout statements within them. These math functions are perfect for some unit tests.

In MathTester.h, create a declaration for a function that tests the Sum function. It doesn't have any input parameters and it doesn't return anything, since this function is meant for us HUMANS and we will read the screen to see if everything passed or not.

The function declaration should look like this:

void Test_Sum();

Within MathTester.cpp we're going to write the definition to this function. We're going to start with these test cases, but convert them into code:

TEST      INPUTS      EXPECTED OUTPUT
------------------------------------------------
1.        2, 3        5
2.        5, 7        12

At the top of the function, let's display a message to show that we're running tests for the Sum function:

cout << endl;
cout << string( 80, '-' ) << endl;
cout << "Test_Sum()" << endl;
cout << string( 80, '-' ) << endl;

We will also need varaibles for the inputs, the expected output, and the actual output:

float num1, num2;
float expectedResult;
float actualResult;

A single test will set the input variables and expected output variable. Then, it will call the function and store the result in the actual result variable. We can use an if/else statement to figure out if the test passed (actual output matches the expected output), or failed (they do not match). We can also display what all these values are to the user to help them see where the test failed.

Our first test will look like this:

void Test_Sum()
{
    cout << endl;
    cout << string( 80, '-' ) << endl;
    cout << "Test_Sum()" << endl;
    cout << string( 80, '-' ) << endl;

    float num1, num2;
    float expectedResult;
    float actualResult;

    // - TEST 1 --------------------------------------------------------
    cout << endl << "TEST 1... ";
    num1 = 2;
    num2 = 3;
    expectedResult = 5;
    actualResult = Sum( num1, num2 );

    if ( actualResult == expectedResult )
    {
        cout << "pass" << endl;
    }
    else
    {
        cout << "FAIL" << endl;
    }

    cout << "* num1             = " << num1 << endl;
    cout << "* num2             = " << num2 << endl;
    cout << "* expectedResult   = " << expectedResult << endl;
    cout << "* actualResult     = " << actualResult << endl;
}

We display the name of the test, we assign values to num1 and num2 (the inputs) and a value to the expectedResult, which we know because we can compute 2+3 ourselves - we are expecting it to give us 5.

Then, we call the Sum function, storing its result in the actualResult variable.

To see if the test passes or fails, we use an if/else statement to check if the actual result and the expected result passed.

Finally, we display what we stored for num1, num2, expectedResult, and what we got for the actualResult. This way, if the test does fail, we can look at the numbers and use that information to try to figure out where it's going wrong.


Add ONE MORE TEST, using the second test set values from before:

TEST      INPUTS      EXPECTED OUTPUT
------------------------------------------------
1.        2, 3        5
2.        5, 7        12

Back in main(), if functionToRun is equal to "tests", then we will call this test function:

Test_Sum();

Run the program with the tests argument. Its output should look like this:

--------------------------------------------------------------------------------
Test_Sum()
--------------------------------------------------------------------------------

TEST 1... pass
* num1             = 2
* num2             = 3
* expectedResult   = 5
* actualResult     = 5

TEST 2... pass
* num1             = 5
* num2             = 7
* expectedResult   = 12
* actualResult     = 12

3. The Slope function

With the Slope function, we're going to start with the test instead. But, we will need to create the declaration for the Slope function, and a definition returning some placeholder data. When the Area function definition is just returning some junk data, it is known as a stub function.

The Slope function will take in two coordinate pairs, which can be represented as four floats: x1, y1, x2, and y2. It will then calculate the slope and return the result, so the return type will also be a float.

Add the following:

  • Slope declaration in Math.h:
    float Slope( float x1, float y1, float x2, float y2 );
  • Slope definition / stub function in Math.cpp:
    float Slope( float x1, float y1, float x2, float y2 )
    {
        return -1; // placeholder
    }
  • Slope tester declaration in MathTester.h:
    void Test_Slope();
  • Slope tester definition in MathTester.cpp:
    void Test_Slope()
    {
        cout << endl;
        cout << string( 80, '-' ) << endl;
        cout << "Test_Slope()" << endl;
        cout << string( 80, '-' ) << endl;
    
        float x1, y1, x2, y2;
        float expectedResult;
        float actualResult;
    }
Implementing the unit test

First we should come up with the test cases. We will use these:

TEST      INPUTS                EXPECTED OUTPUT
--------------------------------------------------------
1.        (1,3), (2,6)          3
2.        (3,3), (7,5)          0.5

Remember the steps of writing a unit test:

  1. Display which test this is (Test 1, Test 2, ...)
  2. Assign values to the inputs (x1, y1, x2, y2)
  3. Assign a value to the expected result
  4. Call the function, assign its return value to the actual result variable
  5. Use an if/else statement to check if the test passed or failed
  6. Display the values of your input variables (x1, y1, x2, y2), the expected output, and the actual output.

Implement the unit tests for both of these.

Calling the unit test

Back in main(), after calling Test_Sum();, add a call to your Test_Slope(); function.

When we build and run the program with the tests input our tests should fail, but this is actually what we want here:

--------------------------------------------------------------------------------
Test_Slope()
--------------------------------------------------------------------------------

TEST 1... FAIL
* x1               = 1
* y1               = 3
* x2               = 2
* y2               = 6
* expectedResult   = 3
* actualResult     = -1

TEST 2... FAIL
* x1               = 3
* y1               = 3
* x2               = 7
* y2               = 5
* expectedResult   = 0.5
* actualResult     = -1

The tests should fail because we just have a function stub, the function returns -1 as a placeholder.

Next, we're going to implement the function, and use the tests to check it out.

Implementing the function wrong

Back in Math.cpp, let's implement the Slope function wrong. We know that test 1 is expecting a result of 3, so let's change the function to just return 3:

float Slope( float x1, float y1, float x2, float y2 )
{
    return 3;
}

Now when we run the program tests one test will pass and one test will fail...

--------------------------------------------------------------------------------
Test_Slope()
--------------------------------------------------------------------------------

TEST 1... pass
* x1               = 1
* y1               = 3
* x2               = 2
* y2               = 6
* expectedResult   = 3
* actualResult     = 3

TEST 2... FAIL
* x1               = 3
* y1               = 3
* x2               = 7
* y2               = 5
* expectedResult   = 0.5
* actualResult     = 3

The first test passes because we just happen to return the number it was expecting, though our "math" is actually wrong. This is why we can't rely on JUST ONE test to verify our work, we usually need AT LEAST TWO TESTS.

Implementing the function right

Going back to the function definition, let's implement it correctly. The equation for the slope is (y2-y1)/(x2-x1), so we can finish writing our function:

float Slope( float x1, float y1, float x2, float y2 )
{
    return ( y2 - y1 ) / ( x2 - x1 );
}

Now when we run the tests, they should both pass:

--------------------------------------------------------------------------------
Test_Slope()
--------------------------------------------------------------------------------

TEST 1... pass
* x1               = 1
* y1               = 3
* x2               = 2
* y2               = 6
* expectedResult   = 3
* actualResult     = 3

TEST 2... pass
* x1               = 3
* y1               = 3
* x2               = 7
* y2               = 5
* expectedResult   = 0.5
* actualResult     = 0.5

Congratulations! You've now done some Test Driven Development!

Calling the Slope function manually

Back in main(), let's add another condition. If functionToRun is equal to "slope", then we will call the function in a few different ways:

cout << "Operation 1: Slope( 1, 3, 2, 6 )" << endl;
cout << Slope( 1, 3, 2, 6 ) << endl;

cout << "Operation 2: x1=2, y1=2, x2=4, y2=4, Slope( x1, y1, x2, y2 )" << endl;
float x1 = 2, y1 = 2;
float x2 = 4, y2 = 4;
cout << Slope( x1, y1, x2, y2 ) << endl;

cout << "Operation 3: x1=3, y1=3, x2=7, y2=5, result = Slope( x1, y1, x2, y2 )" << endl;
x1 = 3;
y1 = 3;
x2 = 7;
y2 = 5;
float result = Slope( x1, y1, x2, y2 );
cout << result << endl;

Once again we're calling the function with literal values (1, 3, 2, 6), and we're also passing in variables as arguments. The last version stores the function's return value in the float result so the result could be used elseware in the program if we wanted.

3. The Area function

Now you're going to implement the Area function and tests on your own based on the requirements. Use the previous two functions as a reference as you work on this one.

Requirements
  • The Area function will take in two parameters: A width and a length. Both of these variables are measurements so they should be floats.
  • The Area function returns the calculated area, so its return type should also be a float.
  • Area can be calculated as length times width.
  • Implement a unit test function with 2 tests.
  • Also practice calling the function in main() in the same ways as the previous two examples.

4. The PricePlusTax function.

Write the function and tests for it based on these requirements:

  • The function takes in two inputs: A price and a tax rate (assume tax rate is like 0.091 for 9.1%.)
  • The function returns the price plus tax, which is calculated as price + price * tax.

Program 4: Character data

⭐⭐

This program will be an example of saving a game character's file. We will create a basic struct to store character information, and use a while loop to ask the user if they want to init the character, update character information, save or load the data.

~/Project$ ./main
-------------------------------
CHARACTER: Riesz
LEVEL:     1
GOLD:      0

I. Init character
E. Edit character
L. Load character
S. Save character
X. Exit

1. Creating the project

We're going to have a struct in our program, as well as a series of functions to help us manage this struct. We will need a .h file for the struct declaration, and a .h and .cpp file for the functions. Create the following files:

  • main.cpp
  • Player.h
  • PlayerFunctions.h
  • PlayerFunctions.cpp

Player.h

Within Player.h, create a new struct named Player. Give it the following member variables:

  • name, a string
  • level, an int
  • gold, an int

Make sure you have your file guards set up in this file, as well as #include statements for any required libraries.

InitPlayer

First, let's create the InitPlayer function. Make sure your function declaration is in the .h file and the definition is in the .cpp file. Don't forget file guards in the .h file, and any required #includes.

Function name

InitPlayer

Inputs

None

Returns

Player

Within this function, do the following:

  1. Declare a new Player variable, such as newPlayer
  2. Set the newPlayer's name to some default value (I used "Riesz"
  3. Set the newPlayer's level to 1
  4. Set the newPlayer's gold to 0
  5. Use the return command to return the newPlayer

Back in main() we can test this out by creating a new Player variable, which can be named anything. For example:

Player myCharacter;

Then, we call InitPlayer. Since InitPlayer returns a Player object, we set the function call to our character variable.

myCharacter = InitPlayer();

For now to test, you can use cout statements to display the myCharacter name, level, and gold.

cout << "CHARACTER: " << player.name << endl;
cout << "LEVEL:     " << player.level << endl;
cout << "GOLD:      " << player.gold << endl;

When you run the program, you should see the default data being displayed to the screen.

CHARACTER: Riesz
LEVEL:     1
GOLD:      0
Make sure to test out your program before continuing!

DisplayPlayer

Next we'll write a function that displays the player's information, so we can call this function instead of having to put those cout statements in our main(), which is kind of ugly.

Function name

DisplayPlayer

Inputs

  1. Player player

Returns

nothing (void)

Move your cout statements from within main() into this function. Make sure you change the name of the variable to match the parameter here!

Back in main(), remove your cout statements and call DisplayPlayer instead, passing in your character object.

DisplayPlayer( myCharacter );
Make sure to test out your program before continuing!

EditPlayer

Function name

EditPlayer

Inputs

  1. Player& player

Returns

nothing (void)

For this function we're receiving a player object directly as a pass-by-reference parameter. We can make changes to the member variables and the updates will show up to the original Player object that was passed in.

Within this function, use cout to ask the user to enter the name, then use getline to get the user to enter a new name. You will probably need a cin.ignore(); prior to the getline statement.

Next ask teh user to enter a level, then get their input with cin >> and store it in the player's level.

Do the same with the gold.

Nothing needs to be returned for this function, since we're updating the data via the pass-by-reference parameter.

In main(), after you call DisplayPlayer, call the EditPlayer function, passing in your Player object. Afterwards, call DisplayPlayer again:

Player myCharacter;
myCharacter = InitPlayer();
DisplayPlayer( myCharacter );
EditPlayer( myCharacter );
DisplayPlayer( myCharacter );

After you enter new player information it should then be updated and show up on the screen.

CHARACTER: Riesz
LEVEL:     1
GOLD:      0

Update name: Angela
Update level: 2
Update gold: 100

CHARACTER: Angela
LEVEL:     2
GOLD:      100
Make sure to test out your program before continuing!

SavePlayer

Function name

SavePlayer

Inputs

  1. string filename
  2. Player player

Returns

nothing (void)

This function will open an output file and write the player's information to that file. Then, it can be loaded in again later on.

Within this function:

  1. Create an ofstream object, open the filename that was passed in as a parameter.
  2. Output the player name, level, and gold to the output file, each on their own line.

Back in main(), call SavePlayer after your previous code. After running the program, look for the save file you specified to make sure the data got saved.

Player myCharacter;
myCharacter = InitPlayer();
DisplayPlayer( myCharacter );
EditPlayer( myCharacter );
DisplayPlayer( myCharacter );
SavePlayer( "savedata.txt", myCharacter );
Angela
2
100
Make sure to test out your program before continuing!

LoadPlayer

Function name

LoadPlayer

Inputs

  1. string filename

Returns

Player

This function will read in the player from the data file, storing it in a new Player object, then return the player.

Do the following:

  1. Create a new Player object, such as newPlayer
  2. Create an ifstream object, open the filename passed in
  3. Use getline to read the name from the file
    getline( input, newPlayer.name );
  4. Read in the level and gold with the input stream operator
    input >> newPlayer.level;
  5. Return the player object at the end.

Back in main, comment out your InitPlayer function call. Instead, replace it with the LoadPlayer function, passing the same file name that you used for SavePlayer.

Player myCharacter;
//myCharacter = InitPlayer();
myCharacter = LoadPlayer( "savedata.txt" );
DisplayPlayer( myCharacter );
EditPlayer( myCharacter );
DisplayPlayer( myCharacter );
SavePlayer( "savedata.txt", myCharacter );

Now when you run the program, the player's data should show up, the same as before you quit the program the last time.

When should we design our function to use the Player return type vs. a Player pass-by-reference parameter?

Generally, we should be preferring function output via the return statement rather than via pass-by-reference parameters. We did it both ways here just to show that you can.

Make sure to test out your program before continuing!

Creating a program loop and menu

Finally, we're going to create a basic program loop and menu in main() that will allow the user to select any of these options in any order. Comment out the other test code you had, but keep your Player object declaration.

Create a done bool varaible as well, and initialize it to false.

Program loop:

An empty program loop will look like this:

bool done = false;
while ( !done )
{
  // 1. Display menu
  
  // 2. Get user selection
  
  // 3. Handle input
}

For the Display menu piece, call the DisplayPlayer function. Afterwards, display the following menu by using cout statements:

I. Init character
E. Edit character
L. Load character
S. Save character
X. Exit

Next, we need to get the user's input. Let's store it as a char variable named choice. We can use a simple cin statement to get their input:

char choice;
cin >> choice;

Now we handle the user's input. Create a series of if/else if statements to look at what the choice variable is storing. Based on the user's selection, we will call the relevant function.

  • If choice is 'I' then call the InitPlayer function.
  • If choice is 'E' then call the EditPlayer function.
  • If choice is 'L' then call the LoadPlayer function.
  • If choice is 'S' then call the SavePlayer function.
  • If choice is 'X' then set done = true, which will cause the program to exit.

Make sure to test each of the menu options to make sure everything is working.

------------------------------------------
CHARACTER: 
LEVEL:     -309917704
GOLD:      32765

I. Init character
E. Edit character
L. Load character
S. Save character
X. Exit
l

------------------------------------------
CHARACTER: Bob
LEVEL:     1
GOLD:      2

I. Init character
E. Edit character
L. Load character
S. Save character
X. Exit