Switch inside while = infinite loop

I'm making a mini dungeon game where you fight a monster till his health goes down to 0.
You have the option to choose if you wanna attack or dodge. if you attack you take 20 points of monster health. I use a switch to choose the option, and I want to make that switch appear till the monster hp doesn't goes down to 0.
So I'm using a While, but what happens is that the while makes his health go down till 0 without asking if the player wanna attack or dodge.

Thanks!

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  #include "stdafx.h"
#include <iostream>

using namespace std;


class player_1
{
public:
	int health = 100;
	int power = 20;

	void attack()
	{
		cout << "Atacking!\n";
	}
};
class Urg
{
public:
	int health = 80;
	int power = 20;

	void stats()
	{
		cout << "Your enemy is monster kind! His name is Urg!\n\n";
		cout << "Stats of Urg:\n"<<health<<" of health\n"<<power<<" of power\n\n";
	}
};

int main()
{
	char y_n;
	char name_1[20];

	int attack_menu = 0;

	Urg u1;
	player_1 j1;

	//Menu 1
	cout << "\t\t\tWelcome to Dungeon V1!\n\n";
	cout << "You wanna start the game? [y]/[n]: ";
	cin >> y_n;
	if (y_n == 'y')
	{
		//Player name
		cout << "Write down your name: ";
		cin >> name_1;
		cout << "Welcome " << name_1 << ", lets start!\n\n";

	}
	else return 0;
	//Menu 1 end


	cout << "Lets fight against your first enemy!\n";
	//Stats of Urg
	u1.stats();
	cout << endl;

	cout << "Choose if you wanna attack or dodge: \n";
	cout << "1. Attack\n2. Dodge\n";
	cin >> attack_menu;

	while (u1.health > 0)
	{
		switch (attack_menu)
		{
		case 1:
			u1.health = u1.health - j1.power;
			cout << "\nYou did 20 damage to Urg.\nUrg attacked back!\n\n";
			j1.health = j1.health - u1.power;
			cout << "Life of Urg: " << u1.health << endl;
			cout << "Life of " << name_1 << ": " << j1.health << endl;
			break;
		case 2:
			cout << "You dodged Urg attack!";
			break;
		}
}
	
	
	

	char f;
	cin >> f;
	return 0;
}
If you choose dodge u1.health will always be > 0 and the while loop will never end.
Thanks, I fixed it, my while wasn't well defined and in a wrong line.
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
	cout << "1. Attack\n2. Dodge\n";
	
	
	while (u1.health >= 1)
	{
	
	cin >> attack_menu;
	if (attack_menu != 1 && attack_menu != 2)
	{
		cout << "1. Attack\n2. Dodge\n";
	}
		switch (attack_menu)
		{
		case 1:
			j1.attack();
			u1.health = u1.health - j1.power;
			cout << "You did 20 damage to Urg.\nUrg attacked back!\n\n";
			j1.health = j1.health - u1.power;
			cout << "Life of Urg: " << u1.health << endl;
			cout << "Life of " << name_1 << ": " << j1.health << endl;
			break;
		case 2:
			cout << "\nYou dodged Urg attack!\n\n";
			break;
		}
}
Topic archived. No new replies allowed.