[CS200.U04.EX] Exercise: Arrays and file loading

CS 200: Concepts of Programming with C++, Summer 2022

🔙 BACK TO UNIT PAGE | CANVAS TURN IN


📝 Assignment

Exercises are meant to be solo effort, please try to complete it on your own. You can ask the instructor or a tutor questions if you get really stuck, but all the information you need to complete the assignment is in here, or in the related reading/lectures.

If you get stuck, please post questions in the Unit 4 'Help!' discussion board.

🔧 Setup

FIRST, from your "My Repls" page on Repl.it create a New folder for this weeks' assignments name it Unit04. Within this folder you will create separate Repl projects for each program. When you turn in the assignments, you will copy the URL to your folder as the submission.

🎁 Submitting your work

First, make sure all your programs are inside your Unit04 folder. If they're not you can click on the three dots on the right side of the program name and click "Move".

PLEASE GIVE YOUR PROGRAMS THE FOLLOWING NAMES:

  • Unit 04 Program 1
  • Unit 04 Program 2
  • Unit 04 Program 3

Clean code also means the ability to find the code itself, so if your project is unkempt and hard to navigate you will lose points.

To submit your work, navigate to the folder for your exercises on replit. Copy the URL to that directory (e.g., https://replit.com/@rsingh13?path=folder/Unit04) and paste it in here in Canvas.

Once you've turned in the assignment, make sure to also post your program in the code review assignment, [CS200.U04.PR] 🔎 Storing data in arrays, loading text - Peer review

💻 Programs

Quick jump: Program 1: Sum from file (Graded) | Program 2: GPA calculator (Graded) | Program 3: Saving and loading data (Graded)

Program 1: Sum from file (Graded)

This program will take in a filename as its input argument. Then, it will open the file, read the numbers, sum the numbers together, and display the result.

~/U04EX_Program1Sum$ ./main numbers1.txt 
5 + 60 + 99 + 100 = 264

1. Program setup

Create a new replit C++ project for this program. You will need to include the fstream, string, and iostream libraries.

The program is expecting one additional argument: an input file.

You will also want to create a couple of text files in your replit project, such as "numbers1.txt" and "numbers2.txt".

Both files should have four numbers in them, separated by spaces. For example, one file could have:

5 60 99 100

You should be able to create an empty program with the argument check by now, so I'm not detailing this part.

2. Creating a traditional array

For this sub-program we're going to use a traditional C++ array, which are still very common in C++ code. The structure of an array declaration is: DATA_TYPE ARRAY_NAME[ SIZE ];

For this program, we need an array of floats and set it to size 4:

float numbers[4];

3. Loading numbers from the text file

Next, let's convert that first argument into a string. Create a string variable named filename and set it to item #1 in the argument list:

string filename = argumentList[1];

Next, we're going to create an ifstream (input file stream) variable, loading in the filename:

ifstream input( filename );

We need to make sure to do a check when we're opening input files, if it fails that means the file wasn't found. If the file wasn't found, we can't continue the program:

if ( input.fail() )
{
  cout << "FAILED TO OPEN " << filename << endl;
  return 2; // Exit with error code 2
}

Now that we have our array of floats and our file opened, we can read in four numbers from the file. If we were reading text from the keyboard, it would look like this:

cin >> numbers[0];
cin >> numbers[1];
cin >> numbers[2];
cin >> numbers[3];

But since we're loading text from the input file, it will look like this:

input >> numbers[0];
input >> numbers[1];
input >> numbers[2];
input >> numbers[3];

4. Calculating the result

Now that we've loaded in the data it's time to add them up. Create a float variable named result. Assign it to the value of all the numbers added together:

float result = numbers[0] + numbers[1] + numbers[2] + numbers[3];

Then, write the result to the screen with a cout statement:

cout << numbers[0] << " + " 
  << numbers[1] << " + " 
  << numbers[2] << " + " 
  << numbers[3] << " = " 
  << result << endl;

5. Testing the program

Build and run the program, passing in one of the text files you created that has numbers in it. The output should look something like this:

$ ./main numbers1.txt 
5 + 60 + 99 + 100 = 264

Make sure to test it with more than 1 input file (with different values in it!) to make sure everything is working OK.

Program 2: GPA calculator (Graded)

⭐⭐

This program will read a text file that contains a list of course and grades and then will calculate the GPA for the semester.

~/U04EX_Program2Gpa$ ./main spring2022.txt 

GRADE REPORT

COURSE    GRADE     
--------------------
CS134     4         
CS200     3.5       
CS210     4         
ASL120    3         

GPA: 3.625

1. Program setup

This program will read in a text file that lists four courses and grade results (4.0 means A, 3.0 is B, 2.0 is C, 1.0 is D, 0.0 is F). Create at least two text files, and fill them with information like this:

CS134 4.0
CS200 3.5
CS210 4.0
ASL120 3.0

Make sure you don't put spaces in the course codes, but separate the course code and grade value with a space.

Create your basic program and do an argument check to make sure the user enters 1 argument, the semester file (e.g., "Spring2022.txt"). Make sure to include the following libraries: iostream, string, fstream, iomanip, and array.

2. Course struct

We're going to create a Course data type with a struct. It will contain a name (string) and a grade (float).

struct Course
{
  string name;
  float grade;
};

Then, within main(), declare an array of 4 courses. We are going to use the array object, a relatively new feature of C++ (as of 2011).

The traditional way to declare an array of 4 courses would be: Course courses[4];

But using the array object, it will look like this: array<Course, 4> courses;

Otherwise, using the array will look pretty much the same.

We will load in the data in a moment.

3. Loading course information from a file

Use argument #1 to get the filename for the input data. Create an ifstream variable and open that filename - make sure to check for a failure, and exit if the load fails.

string filename = argumentList[1];
ifstream input( filename );
if ( input.fail() )
{
  cout << "ERROR OPENING FILE " << filename << endl;
  return 2; // Exit with error code 2
}

Next, we're going to load in each item in sequence. The data in the file looks like this:

CS134 4.0
CS200 3.5
CS210 4.0
ASL120 3.0

So first we're loading course 0's name, then course 0's grade. Then course 1's name, then course 1's grade. And so on:

input >> courses[0].name;
input >> courses[0].grade;

input >> courses[1].name;
input >> courses[1].grade;

input >> courses[2].name;
input >> courses[2].grade;

input >> courses[3].name;
input >> courses[3].grade;

4. Calculating the GPA

Create a float to store the gpa and calculate the gpa as the sum of all the grades, then divided by 4.

5. Displaying all information

Let's draw out a table of the course information. We can use the iomanip library's setw function to set column sizes. The column size affects the following piece of information displayed. The header of our table will look like this:

cout << left
  << setw( 10 ) << "COURSE"
  << setw( 10 ) << "GRADE"
  << endl << string( 20, '-' ) << endl;

the left tells it to left-align (it aligns to the right by default). The first setw sets the column size of the "COURSE" text to 10, so 10 total characters. When COURSE is displayed, there will be some empty space:

COURSE----

(where those -'s will be empty spaces).

The string( 20, '-' ) creates a string of 20 -'s, which make a good table separator between the header and the data.


Next, follow the same format to display each course's name and grade:

cout 
  << setw( 10 ) << courses[0].name
  << setw( 10 ) << courses[0].grade << endl;

Do the same for courses [1], [2], and [3].

At the end, display the calculated GPA as well:

cout << endl << "GPA: " << gpa << endl;

6. Building, running, and testing

Run the program and test it on at least two different text files. The output should look something like this:

$ ./main spring2022.txt 

GRADE REPORT

COURSE    GRADE     
--------------------
CS134     4         
CS200     3.5       
CS210     4         
ASL120    3         

GPA: 3.625

Program 3: Saving and loading data (Graded)

⭐⭐⭐

This program will keep track of a user's bank balance in a text file. When the program runs, it will load in their current balance. It will then ask them how much to deposit and withdraw from their account. After updates are made to the balance, the balance is then saved to the same text file so that it will be saved for next time the program is run.

$ ./main bank.txt

You currently have a balance of $1000.00

How much would you like to deposit?  $50

$50.00 was added to the account

You currently have a balance of $1050.00

How much would you like to withdraw? $235

$235.00 was withdrawn from the account

Updated balance saved to bank.txt

Create a new replit C++ project and add the basic starter code.

You will come up with a solution to meet the requirements and do the coding on your own. However, if you get stuck, feel free to post on the Unit 4 'Help!' discussion board

1. Creating the project

Create a new replit project. Your program will need the following libraries included at the top: iostream, iomanip, string, and fstream.

Also create a text file called bank.txt and enter one number into it, for example:

1000

This file contains the user's bank balance, and we will be loading from and saving to this file.

Requirements

Don't start programming the assignment until you've read the entire requirements section!

Design

Before you begin programming, create a file called pseudocode.txt in your replit project. List out a series of steps that you plan on taking in the program to meet the requirements. Use this as a road map as you begin coding.

Test cases

Any time during the development process, create a file called tests.txt in your replit project. Create at least two test cases, and format your test case file like this:

TEST    INPUTS                EXPECTED OUTPUT
------------------------------------------------
1.      bank.txt has 1000     bank.txt has 1025 after the program ends
        deposit is 50
        withdraw is 25
------------------------------------------------
2.      bank.txt has 500     bank.txt has 460 after the program ends
        deposit is 10
        withdraw is 50
------------------------------------------------
Program specifications
  • Arguments - The propgram only takes 1 argument - the name of the file to read.
  • Variables - You'll need float variables to store the bank balance, a withdraw amount, and a deposit amount. You will also need a string variable to store the filename loaded in from the arguments.
  • Loading the data - Read the filename from argument [1]. Create an ifstream variable and open that file. (If the file fails to load, display an error and return an error code!)
    Load the data into your balance variable, then close the input file.
  • Main program logic - After loading the data, do the following things:
    1. Display the current balance.
    2. Ask the user how much they'd like to deposit.
      If the deposit amount is valid, then add it to the balance.
      If it is not valid, display an error message but continue the program (DON'T modify the balance in this case though.)
    3. Display the updated balance.
    4. Ask the user how much they'd like to withdraw.
      If the withdraw amount is valid, then subtract it from the balance.
      If it is not valid, display an error message but continue the program (DON'T modify the balance.)
    5. Display the updated balance.
  • Save the data - Create an ofstream variable and open the same filename as before. Once it's open, output the value of the balance variable into it, then close the output.
  • Update message - Make sure to tell the user that the file was updated, like "Updated balance saved to bank.txt".
Tips
  • A valid deposit amount is a number greater than 0. (no deposit of $0 or negative amounts!)
  • A valid withdraw amount is a number greater than 0 AND less than or equal to the current balance. (No negative withdraws! No overdrafts!)
  • Remember that you can check if your file opening failed like this:
    if ( input.fail() )
    {
      cout << "FAILED TO OPEN " << filename << endl;
      return 2; // Exit with error code 2
    }
    
Example output

OK run:

$ ./main bank.txt

You currently have a balance of $1000.00

How much would you like to deposit?  $50

$50.00 was added to the account

You currently have a balance of $1050.00

How much would you like to withdraw? $235

$235.00 was withdrawn from the account

Updated balance saved to bank.txt

Invalid deposit:

$ ./main bank.txt 

You currently have a balance of $815.00

How much would you like to deposit?  $-80
Invalid deposit amount! Cannot be 0 or negative.

You currently have a balance of $815.00

How much would you like to withdraw? $10

$10.00 was withdrawn from the account

Updated balance saved to bank.txt

Invalid withdraw:

$ ./main bank.txt 

You currently have a balance of $805.00

How much would you like to deposit?  $100

$100.00 was added to the account

You currently have a balance of $905.00

How much would you like to withdraw? $1000
Invalid withdraw amount! Cannot be 0, negative, or greater than the balance.

Updated balance saved to bank.txt