Elliot Page
Elliot Page

Reputation: 23

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?

Upvotes: 2

Views: 485

Answers (4)

Windyear
Windyear

Reputation: 1

I think that your loop is wrong because the array's index begins with 0.

Upvotes: 0

Daniele Pallastrelli
Daniele Pallastrelli

Reputation: 2552

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");
}

Upvotes: 0

midor
midor

Reputation: 5557

Instead of the built-in array, you can use a std::vector and just push_back score instances for all players, which you then access by index. Alternatively you can also use a std::map/std::unordered_map, if you want to access the scores by player name. These data-structures handle memory-management for you too.

Upvotes: 1

Marko vlaić
Marko vlaić

Reputation: 316

You can have a separate array of type score so the declaration would look as Scores players[input_players] and than init them in a loop.

Upvotes: 0

Related Questions