C++ game help

I am trying to make each player that is entered linked to a number which is their number of lives and I'm not quite sure on how to do it, I need to make for example name[1] have 6 lives also with all other players so name[2] and so on.so that when they lose a live I am able to subtract it from that player

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> //I/O Library -> cout,endl
using namespace std;//namespace I/O stream library created
int main(int argc, char** argv) {

int pp,p1=6,p2,p3,p4,p5,p6,p7,p8,p9,a=1,p,numPlay;//players in the game

  cout<<"How many players are there from 2 to 10?\n";
    cin>>numPlay;
    
    std::string name[10];//stores names
    do{
        
        cout<<"enter player "<<a<<"'s name.\n";
        a=a+1;
        std::cin >> name[a-1];//index goes from 0 to n-1
        
    }while (a<numPlay+1);
        return 0;
}
Last edited on
One easy way you can accomplish this is by using classes.

something like this:

1
2
3
4
5
6
7
8
9
10
11
class Player
{
public:
Player();
int GetLives() { return m_lives; }
std::string GetName() { return m_name; }

private:
int m_lives;
std::string m_name;
};


Then each player object gets its own name and number of lives. However, I assume you have no knowledge of object-oriented programming yet. So here's another way to do it:

1
2
3
4
5
6
7
8
9
int playerLives[10];
std::string players[10];

for (unsigned int i = 0; i < 10; ++i)
{
std::cout << "Enter player " << i << " name: \n";
std::cin >> players[i]; // Note that std::cin does not accept any whitespaces, if you want whitespaces look into std::getline() 
playerLives[i] = 6; // 6 is the number of lives this player has
}


Then say player 4 took damage and died, you can do something like this:

1
2
3
4
5
6
7
8
if (playerLives[4] > 1)
{
--playerLives[4];
}
else
{
// Player[4] has ran out of lives
}


Hopefully this gives you an idea. Note that all code provided by this reply is untested.
Topic archived. No new replies allowed.