A12-Storing Information

Table of Contents


  • Load and save data in text files.
  • Explore code reuse in classes.
  • Code member functions that read data from and write data to file stream parameters.
  • Overload member functions.
  • Write non-member functions that open and close file streams.

Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • You are encouraged to work with one other student of this class following the rules of Pair Programming for Homework Assignments. If you choose to pair program, there is a bonus applied.
  • You may not give a copy of your code to your designated pair-programming partner if you did not develop the code together.
  • You may not look at another person's code until you complete and submit this assignment, except for code you develop code together with your pair-programming partner.
  • You may get help from people other than your pair-programming partner if you get stuck, but only if they do not show or tell you the code to type.
  • Do not copy code from the internet or other sources without attribution. Copying code snippets from the instructor's lesson examples without attribution is allowed.


  1. Make sure you have completed the exercises from lesson 12.
  2. Complete the Review Exercises in CodeLab 12. These exercises will help prepare you for the problem-solving programs and should be completed first.

Project Specifications

Your solutions to these projects must use only techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we have covered, as well as the newer rules, including:

  1. Class naming conventions (See: Class Names)
  2. Indentation in classes and placement of curly braces
  3. Every function declaration (prototype) in the class, including constructor functions, have a function comment block
  4. Every file has a file comment block
  5. No magic numbers (See: No Magic Numbers)

Image source: Ed Parrish

Project 1: File Worksheet

Files are a way to store data that is retained even after a program ends or a computer is turned off. To save data we write to a file. To recover the data, we read from the file.

Use this worksheet to improve your understanding of files, vectors and functions. Refer to lesson 11 and lesson 12 for more information on files.

Project Specifications
  1. Start by downloading the following files and placing them in the same folder:

    Keep the same filenames and function prototypes, adding a function definition to the existing code in filework.cpp to complete the project. Leave the existing code unchanged, except for comments as instructed. Compile the filework.cpp file only, as helper is included in filework. See lesson 13.1.1 and 13.1.2 for information on including files.

  2. Add your name and the date to the file comment block at the top of the filework.cpp file, replacing the words Your Name with your first and last name and Date Here with the current date.
  3. No user input is required for this project and do not add any. All data is read from files.
  4. Write the required functions, one per problem, as described by the function signature and comment block.

    Do NOT change any of the function headers and do NOT make any changes to the main() function besides uncommenting code.

  5. Write the function definitions below main(), and keep their prototypes above main().
  6. Code one cout statement per stream for an error message if a file does not open. Do not add any other cout statement in any function except for uncommenting the cout statements already coded in main().

    Adding cout to debug code is fine but please remove any of those before turning in your code.

  7. After completing each function, uncomment the tests in main() and then compile and run the code to verify correctness. Check the test results and make any alterations to your function definitions as necessary. Do NOT change any code in main() beyond removing comments to call the functions and do not change the function headers.

    When you first start coding you may see warnings when compiling. Remember that code with warnings compiles but the warning is giving you hints about problems with the code.

  8. Example Run: The outputs of the program must look exactly like the following for full credit, including the same order and format of the output. There is no user input.
    *** Testing sumNums ***
    sumNums1 should be 0: 0
    sumNums2 should be 3: 3
    sumNums3 should be 48: 48
    sumNums4 should be 6: 6
    *** Testing countSentenceEnd ***
    countSentenceEnd1 should be 0: 0
    countSentenceEnd2 should be 2: 2
    countSentenceEnd3 should be 3: 3
    countSentenceEnd4 should be 1: 1
    *** Testing avgLineLength ***
    avgLineLength1 should be 9.0: 9.0
    avgLineLength2 should be 8.3: 8.2
    avgLineLength3 should be 10.0: 10.0
    avgLineLength4 should be 8.8: 8.8
    *** Testing deleteOdd ***
    deleteOdd1 should be (0): 0
    deleteOdd2 should be (0,2): 0,2
    deleteOdd3 should be (2,42): 2,42
    deleteOdd4 should be (2,0): 2,0
    *** Testing sumAtLast ***
    sumAtLast1 should be (0,0): 0,0
    sumAtLast2 should be (0,1,2,3): 0,1,2,3
    sumAtLast3 should be (1,2,3,42,48): 1,2,3,42,48
    sumAtLast4 should be (3,2,1,0,6): 3,2,1,0,6
    ***End of Tests***

    Remember that the commas represent newlines in the files your code outputs. Do not save commas in any file.

  9. When all of the tests pass, upload your completed source code file with the rest of the assignment as described in Deliverables.

    Do not submit the helper.cpp file as I have it already.

  • Remember the 5 step Procedure For File I/O in lesson 11.2.5.
  • Remember that reading from a file is like reading data with cin. Solve the problem as you would by asking the user for data and then change cin to fin (or whatever stream name you chose).
  • Remember that reading from a file with a loop like the following can read a bad input value.
    double data;
    while (fin.good()) {
        fin >> data;
    We discussed two fixes for this in lesson 12.1.2: Using Loops to Read Files.
  • If you need to see file data for debugging, then comment the following line at the end of main() and open the files in a text editor.
    // cleanup(fileNames);

    Remember to remove comments on the above line before submitting your completed project.

Image source

Project 2: Job List Manager with Files

We continue to develop our job manager application. We load our data from a file and save our vector of Job objects to a file so we keep the data between uses of the application. The data we work with is automatically loaded when the program starts and saved when the program exits.

When developing this program, use your Job class from Assignment 9 and your job manager code from Assignment 11. We add new code for reading and writing files to store data for our application.

Project Specifications
  1. Using your joblist.cpp source code from assignment 11, save the file as jobfile.cpp before updating the application to load and save the data of the job manager in files.

    Keep the Job class without adding non-specified variables or removing any of the required functions from the last two assignments. Adding member functions is allowed if appropriate. Make sure to correct any errors or problems identified in the last two assignments including incorrect style. Also, make sure to #include <climits> if you use INT_MAX and #include <cstdlib> if you use exit() to ensure the program compiles on all computers.

  2. Your updated program must still operate like assignment 11. You must meet all the same specifications except for those changes described below.
  3. Name the source code file of this assignment jobfile.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  4. Add a second read() member function to your Job class (keeping the original read() function from the last assignment) with the following function prototype exactly:

        Reads data about this Job from the file stream parameter.
        @param fin A file input stream connected to the files with the
        data to load.
    void read(ifstream& fin);
    The functions reads a set of data from the file input stream parameter and stores the data into the member variables of the Job object in the following order:
    1. position (string with spaces allowed)
    2. salary (double)
    3. id (int)

    The function must not open or close the file stream. Opening and closing the stream is handled in the function calling read(). Also, this function must be able to read position names that include multiple words.

    Hint: this function is like the read() function from assignment 11, except for the use of a file input stream (like fin) rather than cin. For an example see lesson lesson 12.3.5. Notice that a job's names may have spaces. Thus you must use getline() to read each job's name. Do not forget about using: fin >> ws to clear whitespace from the input buffer.

  5. Add a non-member function (not part of the class) named loadData() to your program, that calls the read(ifstream&) function from the prior step, to input job data from a file and return the loaded data in a vector of Job objects. Use the following prototype exactly for this function:
        Loads the job data from the specified file name into the vector
        of Job objects.
        @param list The vector of Job objects.
        @param fileName The name of the file from which to read.
    void loadData(vector<Job>& list, string fileName);

    Remember to close the file after loading all the data.

    Hint: for an example of reading file data into a vector of objects, see lesson lesson 12.3.5.

  6. Remove your hard-coded jobs and load from the data file instead. Call the loadData() function at the start of main() with an argument of "jobdb.txt" when the program starts so that it loads the file automatically before any menu code and without any user input.
  7. Prepare and submit a jobdb.txt file that follows the format of this file: jobdb.txt. The data for each job is contained in groups of three lines each in the order:
    1. position (can be multiple words)
    2. salary (decimal numbers)
    3. id (whole numbers)

    Make sure to save jobdb.txt in the UNIX file format with a blank line at the end of the file.

    Hint: to save in the UNIX file format, see lesson 11.2.4. The easiest way is to download the example jobdb.txt file by right-clicking and saving the link directly without any copy-paste. If you update your file on Windows, be sure to save in a UNIX file format.

  8. Add a write() member function to your Job class with the following function prototype exactly:
        Writes information about this Job to the file stream.
        @param fout A file output stream connected to the file in
        which to save the data.
    void write(ofstream& fout) const;
    The function writes the member variables to a file output stream in the following order, each followed by a newline ('\n' or endl):
    1. position (string with spaces allowed)
    2. salary (double)
    3. id (int)
  9. Add a non-member function named saveData() to your program that calls the write(ofstream&) from the prior step to save a vector of Job data into a file. Use the following prototype exactly for this function:
        Writes job data to an output file.
        @param list The vector of Job objects.
        @param fileName The name of the file written.
    void saveData(const vector<Job>& list, string fileName);

    Remember to close the file after saving all the data.

    Hint: This function is like listing to the console but calls write(ofstream&) instead of print(). See lessons 10.4.1 and 10.4.2 for examples of printing and listing data with vectors.

  10. Call the saveData() function when the program exits so that all the current catalog data is saved to a file named list.txt automatically without any user input.

    The output of the saveData() function must save the data in the same format as the input file. Do NOT append the data and do NOT format the numbers differently. Notice the output file name is different than the input file name. The purpose of the different names is to help during program development and grading.

  11. Structure your code to declare non-member function prototypes before main() and non-member function definitions after main() for all your functions.
  12. Submit this project with the rest of the assignment as described in Deliverables.

Extra Credit

The following are worth extra credit points:

  1. Complete the assignment using pair programming. (1 point)
  2. Write a non-member function using the following prototype: (2)
        Writes a report to an output file (extra credit).
        @param list The vector of Job objects.
        @param fileName The name of the file to which to write.
    void writeReport(vector<Job> list, string fileName);

    Add a new menu item 99 to main and call the writeReport() function from main() to produce another text file named report.txt formatted like the following:

    Jobs report:
     # Position                         Salary  Job ID
     1 Engineer                       91010.00    1001
     2 Software Developer            105590.70    1002
     3 Counter Person                 18720.42    1003

Make certain that your README.txt file describes any extra credit attempted.

Tutorial Lab

In preparation for next weeks lessons, complete the following:

  1. Read the assigned reading in the textbook
  2. Complete the Tutorial Exercises in CodeLab 12 before the specified due date.

    Refer to the assigned reading for the next lesson to help you understand the problems. Also, you can use the online lecture notes for more information as the notes become available. You can look at solutions if you miss your first few attempts and are stuck by clicking the "Solution" tab.

Grading Criteria

The instructor will evaluate your assignment using the following criteria. Thus you should check your assignment against these criteria to maximize your score.

Each criteria represents a specific achievement of your assignment and has a scoring guide. The scoring guide explains the possible scores you can receive. Some scoring guides have a list of indicators. These indicators are a sign of meeting, or a symptom of not meeting, the specific criterion. Note that a single indicator may not always be reliable or appropriate in a given context. However, as a group, they show the condition of meeting the criterion.

For information on grading policies, including interpretation of scores, see the syllabus.

Lesson Exercises

  • 2: All lesson exercises attempted and turned in
  • 1: Some lesson exercises completed and turned in
  • 0: No lesson exercises completed or turned in

File Worksheet Functionality

  • 5: All functions completed, compiles without warnings and program generates the correct output without error
  • 4: All functions completed but has a minor error
  • 3: Most functions completed or has some small errors
  • 2: At least half the functions completed or has some errors
  • 1: Few functions completed or has many errors
  • 0: Does not compile or wrong file turned in

Job List Manager with Files Functionality

  • 10: Demonstrates mastery of the assignment
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above) with particularly elegant solutions
    • Compiles without warnings
    • Runs to completion with no abnormal error conditions
    • Generates correct output given correct input
    • Behaves in a reasonable way in response to incorrect data
  • 8: Has all the functionality expected of the assignment
    • Demonstrates many techniques from the lesson
    • Attempts to meet all specifications (see above)
    • Implementation seems more complicated than necessary.
    • May have one minor error
  • 6: Has most of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet all but one of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have 2-3 minor errors
  • 4: Has some of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet at least 1/2 of the specifications (see above)
    • Implementation seems excessively complicated.
    • May have more than 3 minor errors
  • 2: Serious functional problems but shows some effort and understanding
    • Attempts to meet less than 1/2 of the of the specifications (see above)
    • Has a major error or many minor errors
    • Implementation seems very convoluted
    • Demonstrates few techniques from the lesson
  • 1: Does not compile or wrong file turned in
  • 0: Does not execute, not turned in or uses techniques not covered in course

Program Style

  • 3: Code is well-documented including:
    • Correct file name used
    • Name, date, and program description in file comment block
    • Follows specified format for file comment block
    • Has a function comment block for all function declarations following the specified format
    • Proper use of spaces around operators
    • No tab characters are present in the source code
    • As described in How To Document and Organize C++ Code
    • Correct file name used
  • 2: Code has a minor documentation error
  • 1: Code has some documentation errors
  • 0: No apparent attempt to follow documentation standards or write documentation comments

CodeLab and Other Tutorial Exercises

Number completed correctly / number exercises * 8 and rounded up to the nearest integer.

README.txt File

  • 2: README.txt file submitted following the instructions
  • 1: README.txt file submitted but some information was missing
  • 0: No README.txt file submitted

Total possible: 30, plus extra credit


Submit your assignment to Canvas, in the assignment folder A12-Storing Information, following the instructions for submitting homework. Include the following items for grading:

  1. README.txt file
  2. All the exercise files from Lesson 12
  3. filework.cpp
  4. jobfile.cpp
  5. jobdb.txt with a list of jobs

Your assignment must work as submitted, so submit all the files needed to complete your assignment. Remember to test and double check your files before submitting them. If you make a mistake, you can resubmit up to the deadline. If you resubmit, you must include all your assignment files in the last submission as Canvas hides prior submissions.

Last Updated: May 05 2020 @00:54:19