152k views
2 votes
(c++)Jason, Samantha, Ravi, Sheila, and Ankit are preparing for an upcoming marathon. Each day of the week, they run a certain number of miles and write them into a notebook. At the end of the week, they would like to know the number of miles run each day, the total miles for the week, and average miles run each day. Write a program to help them analyze their data. a function to read and store the runners’ names and the numbers of miles run each day;

 a function to find the total miles run by each runner and the average number of miles run each

day;

 a function to output the results.

The output must be in the form of a table where the columns contain

 The runner’s name..... USING STRUCTS rather than arrays.



Here is the file "runners.txt"

Johnson 05 11 12 41 10 10 17

Samantha 20 12 32 04 06 32 24

Ravi 11 22 33 43 55 10 26

Sheila 10 02 03 40 60 20 15

Ankit 09 20 20 10 55 65 81

User Dmitriusan
by
8.2k points

1 Answer

2 votes

Answer:

#include <iostream>

#include <fstream>

#include <string>

#include <iomanip>

using namespace std;

const int NUM_RUNNERS = 5;

const int NUM_DAYS = 7;

struct Runner {

string name;

int miles[NUM_DAYS];

int totalMiles;

float averageMiles;

};

void readData(Runner runners[]) {

ifstream inputFile("runners.txt");

if (!inputFile.is_open()) {

cout << "Error: could not open file\\";

return;

}

for (int i = 0; i < NUM_RUNNERS; i++) {

inputFile >> runners[i].name;

for (int j = 0; j < NUM_DAYS; j++) {

inputFile >> runners[i].miles[j];

}

}

inputFile.close();

}

void calculateTotals(Runner runners[]) {

for (int i = 0; i < NUM_RUNNERS; i++) {

int total = 0;

for (int j = 0; j < NUM_DAYS; j++) {

total += runners[i].miles[j];

}

runners[i].totalMiles = total;

runners[i].averageMiles = static_cast<float>(total) / NUM_DAYS;

}

}

void outputResults(Runner runners[]) {

cout << setw(12) << left << "Runner";

cout << setw(12) << right << "Total Miles";

cout << setw(12) << right << "Average Miles" << endl;

for (int i = 0; i < NUM_RUNNERS; i++) {

cout << setw(12) << left << runners[i].name;

cout << setw(12) << right << runners[i].totalMiles;

cout << setw(12) << right << fixed << setprecision(2) << runners[i].averageMiles << endl;

}

}

int main() {

Runner runners[NUM_RUNNERS];

readData(runners);

calculateTotals(runners);

outputResults(runners);

return 0;

}

Step-by-step explanation:

This program reads the data from the "runners.txt" file and stores it in an array of structs, where each struct represents a runner and contains the runner's name, the number of miles run each day, and the total and average number of miles run. The program then calculates and outputs the total and average miles run by each runner in a table format.

User Allen Lavoie
by
8.0k points