Need some assistance using vectors with classes

Pretty much I have a game where I want the user to enter in a number of players playing against each other. The game is turn based and I'm having trouble.
This is my class:
1
2
3
4
5
6
7
8
9
10
11
12
class fighter
{
public:
	string name;
	int stamina;
	bool alive;
	fighter()
	{
		stamina=0;
		alive=true;
	}
}multi;



I already declared my vector vector <fighter> players

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void multi_data()
	{
		int num_players;
		while(true){
		
		cout<<"How many people will be playing?"<<endl;
		cin>>num_players;
		if(num_players==1)
		{
		cout<<"You can't choose only 1 player in Multi-Player"<<endl;
			system("pause");
			system("cls");
		}
		else
		{
			break;
		}
		}


		for(int i=0; i<num_players; i++)
		{
			players.push_back(multi);
		}
	}
	void multi_fight()
	{
		cout<<"Hello\n";
		for(int i=0; i<players.size();i++)
		{
			
                       cout<<"Please enter in the names of the players"<<endl;
			cin>>multi.name;
			cout<<multi[i].name<<endl;
			system("pause");
			system("cls");
		}
		for(int C=0; C<players.size(); C++)
		{
			cout<<multi[C].name<<endl;
		}
		system("pause");
	}


I'm trying to make it so that they user enters in how many players are playing and have that determine the size of the vector, and after that I want them to enter in a name for every player that is playing.
In line 12 of your first code snippet you declare a global variable "multi" of class player. Then the function multi_data is kinda correctly filling a vector "players", but I'll come back to that later.

In function multi_fight you all read the players' names into that global object multi. As the vector players containes copies of that global object, the players' names in the vector are not modified. Then, line 34 shouldn't compile at all because variable "multi" is not an array. I assume you meant to write players[i].name.

Anyway, you don't need the variable multi at all. Just remove it from your code:
1
2
3
4
5
6
7
8
9
10
11
12
class fighter
{
public:
	string name;
	int stamina;
	bool alive;
	fighter()
	{
		stamina=0;
		alive=true;
	}
}; // here 


To add empty players into vector, replace your line 23 to:
players.push_back(player()); // a nameless object of class player is created and added to the vector

Finally read into the variables stored in the vector, and use them for output:
1
2
3
cout<<"Please enter in the names of the players"<<endl;
cin>>players[i].name; // here
cout<<players[i].name<<endl; // and here 


Same goes for line 40. Good luck!


Last edited on
I did all that and I get:


error C2064: term does not evaluate to a function taking 0 arguments


The error is on the one where you told me to put players()
Oh, sorry for that, I made a mistake in the name of your class.
It should be
players.push_back(fighter());
Topic archived. No new replies allowed.