trying to catch invalid user input

This is a piece of my program, the Dragon() function at the bottom is defined and works as it should in my larger program. I was trying to kick back out invalid inputs and have the user enter a valid one with the while loop. It works as intended for any integer inputs, but if I enter, for example, the letter k, the program starts looping my dragon function indefinitely. Any hints to a direction I should go would be helpful, thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  int main()
{
	srand(static_cast<unsigned int>(time(0)));
	int howMany;
	cout << "How many times do you want the dragon to attack? \nEnter a number between 1-10: ";
	cin >> howMany;

	while (howMany < 1 || howMany > 10)
	{
		cout << "Invalid input. \nEnter a number between 1-10: ";
		cin >> howMany;
	}
		
	for (int i = 0; i < howMany; i++)
	{
		cout << i + 1 << ". ";
		Dragon();
	}
	

	return 0;
}
Last edited on
The problem is that the stream will go into an error state when you type something invalid. You need to clear the error state like so:
1
2
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Remove all remaining [invalid] characters from the stream 


See:
http://www.cplusplus.com/reference/ios/ios/clear/
http://www.cplusplus.com/reference/istream/istream/ignore/
http://www.cplusplus.com/reference/limits/numeric_limits/
thank you!
Topic archived. No new replies allowed.