Reputation: 11
I was wondering how in this situation I can pass a variable from main into a public class function. In this situation the health variable doesn't change at all even though it should. Here's my code:
class PlayerCharacter
{
public:
void SetHealth(int Health)
{
m_health = Health;
}
int GetHealth()
{
return m_health;
}
private:
int m_health;
int m_maxhealth;
};
int main()
{
PlayerCharacter PC;
bool playing = true;
int Choice;
int v1;
int v2;
while (playing)
{
PrintMainMenu();
cout << "Set Health And Max Health" << endl;
cin >> Choice;
v1 = Choice;
cin >> Choice;
v2 = Choice;
PC.SetHealth(v1);
PC.SetMaxHealth(v2);
system("CLS");
}
return 0;
}
Is there something I'm missing here? Thanks.
edit: All of my code
Upvotes: 0
Views: 82
Reputation: 33
In function void PrintMainMenu()
you are creating a new Character.
You need to pass a reference on your Character from main into this function.
Upvotes: 0
Reputation: 60052
From your code link, your PrintMainMenu()
function is creating an entirely new Character
each time. It has no relation to the one being edited in main()
.
You should change it to accept a Character
as a reference and use that to print your stats:
void PrintMainMenu(Character& PC) {
...
}
Upvotes: 2
Reputation: 195
You can try using getline (cin, input) instead of cin>> as reading directly with cin is not type safe and as far as I know, it does not remove newline character. Also, it does not perform length check. So it has been some time not to use C++ but if I remember correctly getline works better.
getline (cin, Choice);
Upvotes: 0