Small Problem

Okay so this is what should be a simple enough code, i just want to create a function that will decrease the nHealth Value by the nAttack Value then output that value the screen.

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
44
45
46
47
48
49
50
51
52
53
54
55
#include "stdafx.h"
#include <cmath>
#include <iostream>

using namespace std;


struct Player
{
	int nHealth;
	int nAttack;
	int nDefense;

};

int Attacked(int nHealth, int nAttack);

int Attacked(int nHealth, int nAttack)
{

	nHealth = nHealth - nAttack;

	return nHealth;
}



int main()
{
	
		cout << "Welcome" << endl;
		
		Player sPlayer1;
		sPlayer1.nHealth = 100;
		sPlayer1.nAttack = 10;
		sPlayer1.nDefense = 50;
		
		char Player1Name[15];
		cout << "Please Enter your Name:";
		cin >> Player1Name;
		cout << "Your Name is: " << Player1Name << endl;
		cout << "Your Health: " << sPlayer1.nHealth << endl;
		cout << "You have been attacked" << endl;
		Attacked(sPlayer1.nHealth, sPlayer1.nAttack);			// function that should change the nHealth Value
		cout << "Health: " << sPlayer1.nHealth;					// Why isnt this out putting 90
		cout << endl;
		cout << endl;
		
		

	int a;
	cin >> a;

    return 0;
}
Your function doesn't do anything to modify your other values. It creates local variables called nHealth and nAttack, but these have no relation to your struct's properties.

It then returns an int, but your code doesn't do anything with this returned value.


Edit:
One option would be to use a reference instead
1
2
3
4
void attacked(int &health, int attack)
{
    health = health - attack;
}



Since this is C++, I would suggest using classes instead, and have "takeDamage()" (or something) be a method in your class.
Last edited on
Topic archived. No new replies allowed.