Unwanted Infinite Loop Occuring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int Guess;


int main()
{
	cout << "CodeMaker, how many chances shall you give the CodeBreaker? --> ";
	cin >> Chances;

	while (!cin)
	{		
		cout << "Please only enter digits for the code. Code = ";
		cin.clear();
		cin >> Chances;
	}




What my problem is, is that when the user enters a non-numeric value, it enters my while loop but infinitely just spams the text inside it. It won't even give me the chance to enter a new value for Chances. Why is this? How can I fix it?
compare to chances in the while statement?

there can be infinitely many things that can make your while statement true. As to fixing it, I have no idea

EDIT: I would also check if the user's input is a digit, I think the code for that is ifdigit(), and since your going to be repeatedly asking a user for information until done right, a do-while loop would look more elegant
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
  int Chances;
  cout << "CodeMaker, how many chances shall you give the CodeBreaker? --> ";
  cin >> Chances;
  while (!cin) {		
    // This is will clear the error bits
    cin.clear();
    // Next you have to clear the stream of the non-integer
    // you don't want.  Remove all characters to the 
    // '\n' is seen before you read again.
    cin.ignore(numeric_limits<std::streamsize>::max(),'\n');
    cout << "Please only enter digits for the code. Code = ";
    // If the trash is not removed, the cin below will try
    // to read the same non-integer again and again and 
    // generate an error.  Then infinite loop
    cin >> Chances;
  }
}
$ ./a.out
CodeMaker, how many chances shall you give the CodeBreaker? --> Testing
Please only enter digits for the code. Code = this 
Please only enter digits for the code. Code = code
Please only enter digits for the code. Code = 4
$

Topic archived. No new replies allowed.