I am trying to loop through the array but Player numbers that have multiple lines are either not accumulating their second instance or getting strange numbers (the last one).
PlayerHitsWalksOuts
1 2 2 2
19 0 5 7
2 0 5 7
18 4 2 0
4 3 3 6
12 2 2 2
7 0 0 9 // should be 7 0 0 6 , because two 7 0 0 3 lines in input file
8 1 4 1
10 2 2 2
3 3 3 6
11 6 0 0
17 4 2 0
9 3 2 1
I am lost on why it's not working since I'm pretty sure I wrote the main() correctly. The class file is correct as well, I believe. When I set the index to 0, I get "Segmentation fault (core dumped)".
#include "Player.h"
#include <iostream>
#include <fstream>
int findNumber(const Player p[], int numPlayers, int playerNumber);
void displayArray(Player team[], int team_size);
int main()
{
fstream fin("baseball.txt");
const int LIST_LENGTH = 20;
int number = 0,
hits,
walks,
outs,
playerIndex,
index = -1,
teamSize = 0;
cout << "This program tracks a baseball player's number "
<< "and their\nnumber of hits, walks, and outs for "
<< "each games in a season.\n";
Player team[LIST_LENGTH];
while (!fin.eof())
{
fin >> number >> hits >> walks >> outs;
playerIndex = findNumber(team, teamSize, number);
if (playerIndex == -1)
{
teamSize++;
index++;
team[index].setNumber(number);
team[index].setHits(hits);
team[index].setWalks(walks);
team[index].setOuts(outs);
}
else
{
team[index].setHits(hits + team[index].getHits());
team[index].setWalks(walks + team[index].getWalks());
team[index].setOuts(outs + team[index].getOuts());
}
displayArray(team, teamSize);
fin.close();
}
}
int findNumber(const Player p[], int numPlayers, int playerNumber)
{
int i;
for (i = 0; i < numPlayers; i++)
{
if (p[i].getNumber() == playerNumber)
return i;
}
return -1;
}
void displayArray(Player team[], int team_size)
{
cout << "\n\nPlayer\tHits\tWalks\tOuts\n"
<< "------\t----\t-----\t----\n";
for (int i = 0; i < team_size; i++)
{
cout << team[i] << endl;
}
}
player.h:
{#include "Player.h"
#include <iostream>
#include <iomanip>
using namespace std;
Player::Player()
{
Number = Hits = Walks = Outs = 0;
}
int Player::getNumber() const
{
return Number;
}
int Player::getHits() const
{
return Hits;
}
int Player::getWalks() const
{
return Walks;
}
int Player::getOuts() const
{
return Outs;
}
void Player::setNumber(int n)
{
Number = n;
}
void Player::setHits(int h)
{
Hits = h;
}
void Player::setWalks(int w)
{
Walks = w;
}
void Player::setOuts(int o)
{
Outs = o;
}
const Player& Player::operator=(const Player & p)
{
if (this != &p)
{
Number = p.Number;
Hits = p.Hits;
Walks = p.Walks;
Outs = p.Outs;
}
return *this;
}
ostream& operator<<(ostream& out, const Player & p)
{
out << setw(2) << p.Number << "\t"
<< setw(2) << p.Hits << "\t"
<< setw(2) << p.Walks << "\t"
<< setw(2) << p.Outs;
return out;
}