A12-Storing Information

Table of Contents


Objectives

  • 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.

Preparation

  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
Image source: Ed Parrish

Project 1: File Worksheet

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

Project Specifications
  1. Start by downloading the worksheet: filework.cpp.
  2. You must name the source code file filework.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.

  3. Add your name and the date to the file comment block at the top of the file.
  4. In addition, download the stars.txt data file into the same folder as your source code.

    Make sure to save stars.txt in the UNIX file format. Download the stars.txt file by right-clicking and saving the link without any copy-paste. Also notice that star names may have spaces. Thus you must use getline() to read the star names.

  5. Have no user input for this project. Testing code for the program is hard-coded in main(). Do NOT use any keyboard input streams, like cin, in this project. If you have a cin statement in your code, you will get a low score.
  6. Instructions for each function are presented in the comment block before the function declaration (prototype). As you write each of functions, uncomment the test code in main to verify your work. Do NOT change any of the function signatures or any code in main() beyond removing comments.
  7. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • Remember the 5 step Procedure For File I/O in lesson 11.2.5.
  • Remember that reading from a file is just like reading data with cin. Solve the problem as you would for asking the user for data and then change cin to fin (or whatever stream name you chose).
  • Remember how the lines in Windows text files end in "\r\n" (see lesson 11.2.2) and that you must save your files in the UNIX file format as discussed in lesson 11.2.4.
  • Remember that fin >> can leave a newline in the input buffer and getline() stops reading when it sees a '\n'. There is a fix for this in lesson 12.1.5.
  • The data in the input file stars.txt is of three different types (string, int, double) repeated in order. We need to read all three types of data in the correct sequence for all three read functions. Here is an algorithm for the readNames function:
    while (fin.good())
      read a string with getline
      push_back the string onto the vector
      read the number of planets into an int variable
      read the distance into a double variable
      clear whitespace from buffer
    
    The above will work with slight modification for the other two read functions as well.

Image
Image Source: Atlas of the Universe [1]

Project 2: Star Catalog Storage

When developing this program, use your Star class from Assignment 9 and your Stellar Catalog code from Assignment 11 to continue developing a program to catalog the nearby stars.

We continue to use a vector of Star objects to hold information about the nearby stars. However, we add code to store the star information in files so the data is available automatically when the program starts.

Project Specifications
  1. Using your stellar.cpp source code from the last assignment, update your application to load and save the data of your stellar catalog in files.

    Keep the Star class without adding non-specified variables or removing any of the required functions from the last two assignments. However, make sure to correct any errors or problems 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. You must name the source code file of this assignment stellar2.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 Star class that reads data from a file input stream and loads the data into the member variables of the Star object in the following order:
    1. name
    2. planets
    3. distance

    Use the following function prototype exactly for this function:

    /**
        Loads information about this Star from the file stream.
    
        @param fin A file input stream connected to the files with the
        data to load.
    */
    void read(ifstream& fin);
    

    This function is like the read() function you wrote in assignment 11, except for the use of an input stream like fin rather than cin. For an example see lesson lesson 12.3.5. Note that this function must be able to read star names that include single or multiple words with spaces between the words. Keep the original read() function from the last assignment.

  5. Add a non-member function named loadData() to your program that loads star data from a file and returns the loaded data in a vector of Star objects.

    Use the following prototype exactly for this function:

    /**
        Loads the Star data from the specified file name and
        returns the data in a vector of Star objects.
    
        @param catalog The list of stars to display.
        @param fileName The name of the file from which to read.
    */
    void loadData(vector<Star>& catalog, string fileName);
    

    The function must call the read(ifstream&) function from the previous step. For an example of reading file data into a vector of objects, see lesson lesson 12.3.5. When opening the file, make certain to call the c_str() member function of string to ensure compatibility with C++98.

  6. Remove your hard-coded stars and load from the data file instead. Call the loadData() function with an argument of "stars.txt" when the program starts so that it loads the file automatically before the menu and without any user input.
  7. You must prepare and submit a stars.txt file and your stars.txt must follow the format of this file: stars.txt. The data for each star is contained in groups of three lines each in the order:
    1. star name
    2. number of planets
    3. distance from Earth

    Make sure to save stars.txt in the UNIX file format. The easiest way is to download the stars.txt file by right-clicking and saving the link without any copy-paste. Notice that star names may have spaces. Thus you must use getline() to read the star names.

  8. Add a write() member function to your Star class that writes the member variables to a file output stream in the following order, each on a new line:
    1. name
    2. planets
    3. distance
    Use the following function prototype exactly for this function:
    /**
        Writes information about this Star 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;
    
  9. Add a non-member function named saveData() to your program that stores a vector of Star data into a file. Use the following prototype exactly for this function:
    /**
        Writes stellar data to an output file.
    
        @param catalog The vector of Star objects.
        @param fileName The name of the file to which to write.
    */
    void saveData(const vector<Star>& catalog, string fileName);
    

    This function must call the write() function from the previous step. This function is like listing to the console but calls write() instead of print(). See lessons 10.4.1 and 10.4.2 for examples of printing and listing vectors data. When opening the file, make certain to call the c_str() member function of string to ensure compatibility with C++98.

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

    The output of the saveData() function must save the data in the same format as the input file. For instance, 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. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • For how to save in the UNIX file format, see lesson 11.2.4.
  • For an example of reading file data into a vector of objects, see lesson 12.3.5.
  • Do not forget about using: fin >> ws to clear whitespace from the input buffer.

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:
    /**
        Writes a report to an output file (extra credit).
    
        @param store The vector of Star objects.
        @param fileName The name of the file to which to write.
    */
    void writeReport(vector<Star> catalog, string fileName);
    

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

    Stellar catalog report:
                                     Distance from Earth In
     # Star               # Planets      Miles  Light Years
     1 Sun                        8   9.31e+07     1.58e-05
     2 Proxima Centauri           1   2.48e+13     4.22e+00
     3 Epsilon Eridani            1   6.17e+13     1.05e+01
    
    Closest star to Earth: Sun
    Farthest star from Earth: Epsilon Eridani
    Average number of planets: 3.33
    

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

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

Stellar Catalog Storage Functionality

  • 10: Demonstrates mastery of the assignment
    • Applies concepts from the lessons appropriately
    • Meets all specifications (see above) with particularly elegant solutions
    • 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

  • 4: Code is well-documented including:
  • 3: Code has a minor documentation error
  • 2: Code has some documentation errors
  • 1: Code has many 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

Deliverables

Submit your assignment to Canvas, in the assignment folder that matches the name of this assignment, 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. stellar2.cpp
  4. stars.txt with stars for catalog

You must submit all the files needed to complete your assignment. Do not assume that the instructors has any files. Your assignment must work as submitted.

Last Updated: May 08 2017 @14:25:01