you were just told that the infinite loop is because the condition never changes...
A
completely separate problem is too high (or too low) of an entry. In this case you may overrun the cin buffer and so it ends up being in erroneous state for the remainder of the loop. To clear cin errors, cin.clear(), and to ignore the remainder of the line, use cin.ignore(...).
What was actually happening in your case for big numbers was that cin was in erroneous state and the input was set to 2147483647. As an int, it can never be greater than 2147483647 and so the ">" comparison was just pointless. Pick a more sensible max for health.
Other tips:
- Prefer constants instead of defines (which do a lot more replacing than you may think).
- Limit the things you put in global scope.
- Prefer to capitalize classes, especially if you're using namespace std. Those are lowercase on purpose.
- If you're making a class with everything public, you might as well use a struct.
- Prompt the user with info about what's expected. As you had it, the user might think the program froze, not realizing it wants input. (Yes, today you are the user, but think of tomorrow)
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
|
#include <iostream>
#include <string>
#include <limits>
using namespace std;
struct Player {
string name;
int health;
int coins;
bool isDead = false;
};
int main()
{
const int MIN_HEALTH = 1;
const int MAX_HEALTH = 20000;
Player p;
int x = 1;
int times = 5;
cout << "Enter health ("<<MIN_HEALTH<<"-"<<MAX_HEALTH<<") " << times <<" times\n";
while (x<=times)
{
cout << "#" << x << " ";
cin >> p.health;
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
if (p.health > MAX_HEALTH) {
cout << "Health Value too high!" << endl;
}
else if (p.health < MIN_HEALTH) {
cout << "Health value cannot be set below 1." << endl;
//p.isDead = true;
}
else {
cout << "Health Value set to: " << p.health << endl;
}
x++;
}
cout << "You are dead!" << endl;
return 0;
}
|
can run it at
https://repl.it/@icy_1/RunnyWellmadeTranslations