Contents

Instructions

This lab will give you experience with 1D arrays as well as file input/output.

Part 1: Basic File IO + Static Arrays

In this part, you will read in a file with 5 lines into a static array. Reading from a file is similar to using cin, but there are some extra things you have to do, like opening and closing the file. You should read the topic page on File IO to understand how to use it.

In sublime, create a new text file and save it as names.txt. In it, write down five names (these can be made up or names of friends or family), one name per line.

Now create a new C++ file called lab8-part1.cpp. Copy the following code into it:

Now write the code that corresponds to each of the comments in main.

Part 2: Reading a variable sized file

In this part, we will up the ante. Rather than only reading the first five lines of a file, we'll read the whole file. Moreover, we'll let the user specify the file! This, of course, means we'll need to use dynamic rather than static arrays, since we won't know the size of the array (i.e., the number of lines in the file) until the user actually chooses a file and we see how many lines it has.

Create a new file called lab8-part2.cpp and copy the following code to it. Then complete the program.

Part 3: Reading structured data from a file

Just reading lines from a file is a little boring. A more interesting use of files is to store information that we can read into a struct. That's what you'll do in this part.

Start by making a new text file called contacts.txt. In it, copy the names you entered in names.txt. For each name in the file, type an address for that person on the line below, and their phone number on the line below that. For example, here's a file with two entries (one for Barack Obama, and another for Doc Wylie):

Barack Obama
1600 Penn. Ave NW, Washington, DC
555-555-5555
Dr. Richard Wylie
376 Hale St., Beverly,  MA
444-444-4444

Now create a C++ file called lab8-part3.cpp and copy the code below to it. Complete the program.

Submission

Submit your .cpp files to here. You can view the rubric here.

(Back to top)