Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Extend this program to display which player has the highest batting average (hit

ID: 3756666 • Letter: E

Question

Extend this program to display which player has the highest batting average (hits / atBats) and that average using the text file below.

#include <iostream>

#include <string>

#include <fstream>

using namespace std;

// Structure to hold batting statistics

struct Player

{

string name;

int atBats;

int hits;

};

int main()

{

ifstream statFile;

string playerName;

int bats, hits;

Player * baseballArray[100];

Player * aPlayer;

int numPlayers = 0;

statFile.open("stats.txt");

// Continue reading until the end of file

while (statFile >> playerName)

{

statFile >> bats >> hits;

// Dynamically create a new Player

aPlayer = new Player;

aPlayer->name = playerName;

aPlayer->atBats = bats;

aPlayer->hits = hits;

// Store the pointer to the Player struct in the array

baseballArray[numPlayers++] = aPlayer;

// Display this information

cout << aPlayer->name << " has " << aPlayer->atBats << " at bats and "

<< aPlayer->hits << " hits" << endl;

}

// For Activity 3: Display which player has the highest batting average.

// Display the player's name and average

}

=============================================stats.txt

Andrus 574 148
Beltre 543 151
Choo 531 146
Fielder 592 182
Odor 405 108

Explanation / Answer

#include <iostream>

#include <iomanip>
#include <cstdlib>
#include <string>
#include<stdlib.h>
#include <fstream>

using namespace std;

// Structure to hold batting statistics

struct Player

{

string name;

int atBats;

int hits;


};

int main()

{

ifstream statFile;

string playerName,maxPlayer;

int bats, hits,a,b;
float avg,maxavg=0;

Player * baseballArray[100];

Player * aPlayer;

int numPlayers = 0;

statFile.open("stats.txt");

// Continue reading until the end of file

while (statFile >> playerName)

{

statFile >> bats >> hits;

// Dynamically create a new Player

aPlayer = new Player;

aPlayer->name = playerName;

aPlayer->atBats = bats;

aPlayer->hits = hits;
avg=float (hits) / bats;

if(avg>maxavg)

{

maxavg=avg;

maxPlayer=playerName;

}
// Store the pointer to the Player struct in the array

baseballArray[numPlayers++] = aPlayer;

// Display this information

cout << aPlayer->name << " has " << aPlayer->atBats << " at bats and "

<< aPlayer->hits << " hits" << " has batting average "<< avg << endl;


}

// Display the player's name and average

cout<<“The highest batting average is “<<maxavg<<“ for player “<<maxPlayer;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote