Skip to main content

Section 15.12 Case Study: Students - Part 2

We now have a way to turn data in strings into a Student struct. We still are missing code to read in from the file and also missing code to calculate the average.We can work on these parts in whatever order we like. If we want to do calculations, we can create some test students in code and use them for calculations. If we want to work on the input, we can read from the file and create students, then verify those.
Our code for the calculations will be easier to verify as they do not involve IO. So lets tackle them next.

Subsection 15.12.1 Calculating One Average

Eventually, we want to calculate the average for each student. But it will be easier to start with just calculating the average for a single student. If we build a function to do that, we can then call that function with each of the students.
The function to calculate an average doesn’t even need to know about the entire student. It just needs access to the vector of scores. So it might look like:
Listing 15.12.1.
double calculateAverage(const vector<double>& scores) {
    double total = 0.0;
    for (double score : scores) {
        total += score;
    }
    return total / scores.size();
}

Checkpoint 15.12.1.

Given the function above, assuming you have a student variable s, complete this code to calculate the student’s average and store it as a double called avg?
  • double avg = calculateAverage(s.scores);
  • double avg = s.calculateAverage();
  • calculateAverage is not a member function
  • calculateAverage(avg, s);
  • calculateAverage is a pure function that returns a result
  • double avg = calculateAverage(s);
  • calculateAverage takes just the student’s scores, not the entire student
  • calculateAverage(s.scores);
  • That does nothing with the average that is returned

Subsection 15.12.2 Calculating all the Averages

Now we want to calculate multiple averages and print them all. Because we are going to be printing the data, it will be hard to use doctest unit tests. Instead, we will simply run a program with some test data and examine the output to see if it looks correct.

Checkpoint 15.12.2.

main has code to build multiple students. Add code to loop through the students and print the first name and average score for each. Put each student on a separate line and use a single space between the name and score:
Hint.
If you are stuck, start by looping through the students vector and just printing each first name. Accessing a first name should look something like s.name.first. Once that is working, use the calculateAverage function on each student’s scores.
You have attempted of activities on this page.