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 |
Function Rules
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 |
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++
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 | |
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; | |
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. |
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.
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
Here are program outlines/algorithms for the makeADeal.cpp file:
initialPrompt
swapDoors
promptSwap (this function is completed for you -- do not change it)
playRound
main (this function is completed for you -- do not change it)
Note: The above code uses random number generation. This is defined in the <cstdlib> library. |
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. |
Program Design - Function Parameters and How to Pass Them
The makeADeal.cpp file has an outline of the functions required by this program.
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 | |
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! |
Paste your code here for the swapDoors function:
Paste your code here for the playRound function:
|
|
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)
void redactInfo(string redactedWord, string& sentence)
int main()
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:
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? | |
Paste your code here:
… continue on the next page if you need more room
|
… 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.
|
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 |
| |
| |
| |
| |
| |