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.