-2
struct Player {
  int money=1500;
  int position=1;
  //Position positionn;
  //int number;  // number of player
  bool eliminated =false;
};

I have this in main:

cout <<"Enter the number of players:";
  cin >> numOfPlayers;
  //between 2-8 ? how
  for (int i=0; i<numOfPlayers; i++)
  {
    Player player[i]; 
  }

1)how do I store the values from the for loop?
2)How do I put this in a separate function but still have the values passed into main?

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
Tariq Saba
  • 13
  • 2
  • 4
    I recommend that you [get a few books to read](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). And more specifically learn about [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). – Some programmer dude Oct 25 '18 at 18:40

1 Answers1

1

You could do something like this:

#include <iostream>
#include <vector>
#include "Player.hpp" // Your header file for Player struct.

int main()
{
  std::cout << "Enter player quantity: ";
  unsigned int quantity;
  std::cin >> quantity;
  std::vector<Player> game_players(quantity);
  //...
  return EXIT_SUCCESS;
}

See constructors for std::vector.

Edit 1 - Dynamic allocation
If you are not allowed to use std::vector or must use arrays, this is one method:

int main()
{
    std::cout << "Enter player quantity: ";
    unsigned int quantity_of_players;
    std::cin >> quantity_of_players;
    Player *  p_players = new Player[quantity_of_players];
    //...
    delete [] p_players;
    return 0;
}

The above code fragment allocates the container of player in dynamic memory (a.k.a. heap), since the quantity is not known a compile time. The memory is deleted prior to returning back to the operating system.

Edit 2: Passing the players
You would pass the container of Players by using references:

void Print_Player_Info(const std::vector<Player>& players)
{
   for (unsigned int i = 0; i < players.size(); ++i)
   {
      std::cout << "Player " << i << ":\n";
      std::cout << "    money: " << players[i].money << "\n";
      std::cout << "\n";
   }
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154