1 of 16

Lab 9: Functions, Strings, and File I/O Streams

Due Saturday Oct 31, 2020 at 11:59PM EDT on Gradescope. NO EXCEPTIONS! Your lab MUST be submitted to Gradescope by the deadline or you will not receive credit! This lab is worth 40 points and is graded for completion. However, earning a grade depends on attendance and participating during the lab - this will be verified by the staff member joining your meeting.

Lab meetings last 90-120 minutes. You work as a group for the first 60 minutes and a member of the course staff will join your call for the next 30 minutes to check-in and answer questions. The remaining 30 minutes are there if you need them.

Introductions

Welcome to Lab! Before jumping in to the worksheet, encourage your team to warm up by each taking a turn giving your response to the following question to the group:

What problem or situation did TV / movies make you think would be common, �but when you grew up you found out it wasn’t as much of a problem as you thought?

REMINDER: If you get stuck on one of the exercises, feel free to move on and come back to it after checking in with your Coach. We are happy to answer any questions!

HEADS UP: If a question says Person D or E is the discussion leader, but you don't have that many members, the Leader should lead the discussion for that question.

Our team name is...

Name

Time joined

call

Roles

(groups of 3)

Roles

(groups of 4)

Roles

(groups of 5)

Person A

Coder

Coder

Coder

Person B

Questioner

Googler

Questioner

Googler

Questioner

Person C

Leader

Scribe

Leader

Leader

Person D

Scribe

Scribe

Person E

Googler

Staff

Coach

2 of 16

Function Rules

  • You can have multiple parameters
  • You may return AT MOST one variable
  • You MUST specify a return type for the function name
  • Functions MUST be declared before they are called (used) in your code
  • The return variable from a function will be used by the caller via its declared type

Strings

Strings are sequences of characters. You need to include the <string> library in order to use strings (#include <string>). Use the table below as a helpful resource for yourself on how to use strings in C++.

Function Name/Usage

Returns

What It Does

str.size()

int

Returns the size of a string

str.at(index)

char

Returns the character at index but will cause a SIGABRT error if index is less than 0 or greater than str.size() - 1

str[i]

char

Returns the character at index i, but will cause a SEGFAULT if i is less than 0 or greater than str.size() - 1

str.find(str2)

int

Returns the starting index of the first occurrence of str2 in str. If str2 does not occur in str, str.npos is returned

str.npos

int

Value returned by str.find(str2) if str2 is not found in str. If value is stored as an int, value = -1

str.replace(index,len,str2)

string

Removes len characters from str starting at index and then inserts str2 at index

str.empty()

bool

Returns TRUE if str.size() == 0 ("") and FALSE otherwise

3 of 16

Warmup (Estimated Time: 10 Minutes)

Functions

Before we dive in, let’s take a minute to review functions in C++. Just like in MATLAB, functions are a great way to accomplish the same task multiple times with different parameters and clean up code.

Declaring a Function in C++

  • Return type: the type (eg. int) of the return value (data coming out of the function)
  • Function name: the name of the function
  • Function parameters: variables passed as parameters to the function (you must specify their types)
  • Return value: use the return keyword to return a variable or value

Consider the add function above. Type the corresponding part of the function next to the elements listed below.

Part of the Function

What this part is in the add function

Person A

Return type

Person B

Function name

Person C

Function parameters

Person D

Return Value

Person E

Function parameter types

4 of 16

Given the text file file.txt and the script main.cpp, shown below, fill out the table with your predictions of the function’s output to the terminal if the given expression replaced the comment on the final line of the code block. The Coder should run the functions in C++ to check whether the predictions are correct.

file.txt

inside of main.cpp

Fill in the table below with your guesses of the output from main.cpp.

Natalie (nat) has lost her cat.

Dan the man has a plan to open the can.

ifstream in("file.txt");

string line1, line2, test;

String sub = "cat";

getline(in, line1); // line1 contains “Natalie (nat) has lost her cat”

getline(in, line2); // line2 contains “Dan the man has a plan to open the can.”

in.close();

// Test Expression Here

Discussion Leader

C++ Test Expression

Prediction

Person B

test = line1.at(6);

cout << test << endl;

Person C

cout << line1.find("cat") << endl;

Person D

cout << line2.replace(0,11,"Katherine's canary") << endl;

Person E

cout << line1.replace(line1.find(sub),...

sub.size(),"duck") << endl;

5 of 16

File Input and Output Streams

So far, we have worked with variables created during program execution or read with cin. In many cases, we want to save data to use after the program finishes, or to load previously generated data from a file. The filestreams ifstream and ofstream allow us to read from files and write to files.

Fill in the blank boxes of the table below to create a useful reference for yourselves.

Function Name/Usage

What It Does

ofstream outFile;

Creates the variable inFile of type ifstream

Links the variable inFile to the file “exmpl.txt” to read from

outFile.open("OutputFile.txt");

Links the variable outFile to the file “OutputFile.txt” to read from

outFile.close();

inFile.close();

int a = 0;

inFile >> a;

Returns a true/false value after checking if the stream inFile has failed.

6 of 16

Let’s Make a Deal! Exercise (Estimated Time: 40 Minutes)

Download makeADeal.cpp. Attach the completed .cpp file to your submission.

Your task is to write a program to play the game Let’s Make A Deal. This exercise will require functions, loops, and if statements.

The game works like this:

  1. The host asks the contestant to randomly choose door 1, 2, or 3. Behind 2 of the 3 doors are goats, but behind 1 of the doors is a brand new car.
  2. The host knows which door the car is behind and reveals to the contestant one of the “goat doors” that is neither the contestant’s chosen door nor the winning “car door”.
  3. The host gives the contestant the option to switch doors (i.e. keep the door he/she originally chose or swap with the remaining, unrevealed door).
  4. The contestant makes the decision to swap or not, and the winning door is revealed.

Program Design - High Level Organization

Below is a schematic, or visual plan, of the organization of the makeADeal program. The schematic shows how the helper functions interact with the main function and with each other.

Important!

Do NOT start writing code yet! Read through the next pages so we can describe how this program works and how it is organized. You will be less frustrated if you do this reading before coding!!

gets info from contestant; use initialPrompt()

print summary of game

initialPrompt

iterate the number of rounds to play

playRound()

playRound

promptSwap

swapDoors

main

7 of 16

Here are program outlines/algorithms for the makeADeal.cpp file:

initialPrompt

  1. Prompt the contestant to enter their name
  2. Read in contestant's name
  3. Prompt the contestant for how many rounds they would like to play
  4. Read in number of rounds
  5. Print welcome message using contestant name, e.g. �<Player>, welcome to Let's Make a Deal!

swapDoors

  1. Check to see if the contestant wants to swap doors
    1. If yes, set the contestant’s door equal to the remaining, unrevealed door
    2. Otherwise, do nothing

promptSwap (this function is completed for you -- do not change it)

  1. Choose a door to reveal to the contestant (this should be a “goat door”)
  2. Print out a statement that the door has a goat
  3. Determine which door is the “remaining door” (not selected by the player and not revealed)
  4. Prompt the contestant for if they would like to swap their door for the “remaining door”
  5. Call the swapDoors function

playRound

  1. Randomly decide winnerDoor using (rand()%3)+1) (THIS STEP IS DONE FOR YOU) Note: The rand() function comes from the cstdlib which is included at the top. The above line of code will choose a random number between 1 and 3.
  2. Print the round number and a prompt for the contestant to choose door, and read in answer
  3. Call the promptSwap function
  4. Print out the winning door
  5. Checks whether the playerDoor matches the winnerDoor
    1. If they match, print “You win!” and increment numWins
    2. Otherwise, print “Better luck next time!”

main (this function is completed for you -- do not change it)

  1. Declare necessary variables
  2. Call the intialPrompt function
  3. Use a loop for the number of specified rounds
    1. Call the playRound function on each iteration of the loop
  4. Print out the total number of wins

Note: The above code uses random number generation. This is defined in the <cstdlib> library.

8 of 16

Testing the Let’s Make a Deal Program

Once your program is complete, you will be able to run it and test it to ensure your output looks ~similar~ to what is shown below. NOTE: Your results will likely be slightly different due to the randomness of the game.

If a contestant plays one round:

If a contestant plays two rounds:

Enter contestant name: Rick

How many rounds do you want to play? 1

Rick, welcome to Let's Make a Deal!

Round 1: Would you like door 1, 2, or 3? 1

Door number 3 has a goat!

Would you like to swap door 1 for door 2? (Y/N): N

The winning door was door 2

Better luck next time!

Rick won 0 out of 1 rounds.

Enter contestant name: Laura

How many rounds do you want to play? 2

Laura, welcome to Let's Make a Deal!

Round 1: Would you like door 1, 2, or 3? 2

Door number 1 has a goat!

Would you like to swap door 2 for door 3? (Y/N): Y

The winning door was door 2

Better luck next time!

Round 2: Would you like door 1, 2, or 3? 3

Door number 1 has a goat!

Would you like to swap door 3 for door 2? (Y/N): Y

The winning door was door 2

You win!

Laura won 1 out of 2 rounds.

Before you code!

There is a lot going on with this program: four helper functions plus the main function. Let’s come up with a plan for how to complete this program before we start typing away.

9 of 16

Program Design - Function Parameters and How to Pass Them

The makeADeal.cpp file has an outline of the functions required by this program.

  • Two of the functions (promptSwap and main) are complete for you.
  • The playRound function has the function header and step 1 of its algorithm completed, but needs the rest of the implementation written.
  • The initialPrompt and swapDoors functions need to be fully defined (function header + implementation).

Before you start completing the missing code, take two minutes to look at the description of the parameters for the initialPrompt and swapDoors functions and determine the type of these variables and how these parameters should be passed.

Refer back to the algorithm outlines of the functions to determine how, where, and when the values of variables need to change in order for the program to work. HINT: Each function has at least one variable that should be passed by reference. Make sure to think about when pass-by-reference should be used and which variables this logic applies to!

The Leader should start the discussion about the parameters, and then the group should come to a consensus about the type of the parameters and how to pass them to their function. The Scribe should complete the table below with the group’s decisions.

Function

Type

(int, double, string, or bool)

Parameter

How to pass in the parameter

(pass by value or

pass by reference)

initialPrompt

name

totalRounds

swapDoors

answer

playerDoor

remainingDoor

10 of 16

Complete the Let’s Make a Deal! Program

We want you to practice collaborating on programs, so for this exercise, divide up the work for the three functions according to the table below. You can still help each other figure things out when you get stuck, though.

Okay, NOW you can start coding! When you have completed your code, copy your versions of the three functions into the corresponding boxes on this slide and the next slide.

Paste your code here for the initialPrompt function:

Person

Function

Person A

initialPrompt

Person B

swapDoors

Person C, D, & E

playRound

Did You Know?

This program is the premise of a statistical paradox commonly referred to as the Monty Hall Problem. According to the problem, your probability of winning is much higher if you swap rather than keeping your original door!

11 of 16

Paste your code here for the swapDoors function:

Paste your code here for the playRound function:

12 of 16

Redacting Data Exercise (Estimated Time: 40 Minutes)

Download redactInfo.cpp, experimentNotes.txt, and depositionNotes.txt.

When researchers conduct experiments or studies with

human subjects, they often need to collect and record

identifiable information about the subjects, including names,

pronouns, medical information, etc. For privacy reasons, it is

important to redact any of this identifiable information before

the study can be shared publicly.

In this exercise, you will be writing a program to redact

sensitive information from text files containing notes from

an experimental study and a deposition.

(Image (right) source: https://www.canadianbusiness.com/innovation/knote-document-redaction-ai/)

Use the following program outlines/algorithms to complete the redactInfo.cpp file:

string createAsterisksWord(int numAsterisks)

  1. Initialize an empty string (this will become your string of asterisks)
  2. For the number of asterisks passed in numAsterisks:
    1. Concatenate asterisks onto your string
  3. Return the string

void redactInfo(string redactedWord, string& sentence)

  1. Declare a variable and store the length of the redacted word
  2. Declare a replacementWord string containing the correct number of asterisks, equal to the length of the word you are redacting
    1. Hint: Use your createAsterisksWord() function
  3. While redactedWord is still in sentence:
    • Find the position of redactedWord
    • Replace redactedWord with replacementWord

int main()

  1. Prompt the user to input a redactedWord (this is the identifiable information that must be removed from the file)
    1. Hint: the redaction could be multiple words, so be sure to read the whole line entered by the user (consider >> vs getline())
  2. Prompt the user to input the name of the file to read from
  3. Open the file
  4. Make sure opening the file was successful
    • If the file isn’t open, return 1

13 of 16

  • While there are more sentences to read in the file (each line of text in the file is one sentence):
    • Read the sentence/line from the file
    • Modify the sentence by implementing and calling redactInfo()
    • Print the modified sentence to the terminal
  • Close the file

Work collaboratively, similar to the Let’s Make a Deal program, to complete this program.

Testing

Ensure your output looks like this:

Run additional tests on your program:

  • Redactions: Gonzales, him, i
  • Notes files: experimentNotes.txt and depositionNotes.txt
  • Other things you can think of!

Observe what your program produces for the redacted experiment notes. The Scribe should record your observations in the table below:

bash-4.1$ ./redactInfo

Enter the redacted word(s): Jonas Gonzalez

Enter the file to read from: experimentNotes1.txt

************** participated in the study on 10/15/2020.

After 15 minutes, ************** completed the first exercise.

The second exercise took him 10 minutes.

************** said the second exercise was more intuitive to solve.

Things that worked the way we expected them to

Things that did NOT work the way we expected them to

What revisions could we consider changing in order to have the program work better?

14 of 16

Paste your code here:

… continue on the next page if you need more room

15 of 16

… continue your code here if you need more room. If you do not need more room, please type ALL DONE in this box so you won’t lose points.

16 of 16

Time with course staff

The Questioner is responsible for recording any questions the team has for the staff member. Make sure you write down your questions even though you're asking them out loud so that we can tell from your worksheet that the team was actively thinking of questions to ask.

Submit worksheet

Submit the lab worksheets to Gradescope by Saturday at 11:59PM. We strongly recommend submitting your worksheet the same day that you meet as a group! Your lab MUST be submitted to Gradescope by the deadline or you will not receive credit! NO EXCEPTIONS!

The Scribe is responsible for making the final submission to Gradescope. You need to add your other group members to the submission after it is uploaded using this link:

Your team's question

Summary of staff answer