Elliot Page Elliot Page - 1 month ago 15
C++ Question

C++: How can I create a number of members of a class depending on the input from the user?

I am trying to make a simple multiplayer game in C++, which needs to be able to have a variable number of players. I thought I could handle this by creating a class with the 'score' values for each player and then each player would be a separate member of the class.

int main(void)
{

int input_players;

cout << "Welcome to Pig" << endl;
cout << "Please enter the number of players: ";
cin >> input_players;

int *playersarray = new int[input_players];

for (int i = 1; i <= input_players; ++i)
{
playersarray[i] = i;
//scores playersarray[i];
cout << playersarray[i] << endl;
}

system("PAUSE");
}

class scores
{
public:
int last_roll;
int turn_total;
int total_score;
};


In the for loop, you can see my problem where I am trying to create the number of players by creating different members of the class where the line has been commented out. As I do not know how many players will be playing each time, I cannot declare the members as normal. for example:

scores player1
scores player2
scores player3


Is there anyway I can create the number of members depending on number input by the user?

Answer

You can write a Player class (after all, you're dealing with "players" :-), and then using a size variable container (e.g., std::vector) to hold your players.

Something like this:

class Scores
{
public:
    int last_roll;
    int turn_total;
    int total_score;
};

class Player
{
public:
    Scores scores;
    ...
};

int main(void)
{
    cout << "Welcome to Pig" << endl;
    cout << "Please enter the number of players: ";

    int input_players;
    cin >> input_players;

    std::vector< Player > players;

    for (int i = 0; i < input_players; ++i)
    {
        // insert in players vector a new Player with scores
        // last_roll=1, turn_total=2, total_score=3
        players.push_back( Player{ Scores{ 1, 2, 3 } } );
        ...
        // print the total_score of i-th player:
        cout << players[i].scores.total_score;
    }

    system("PAUSE");
}