Infinite loop in while statement with cin

Why does this loop run infinitely?? Shouldn't it pause and allow me to make a new entry? Instead it just prints "How many players ....? - Error message 2" infinitely ... Obviously, I tried to use the uncommented ignore in case there was a return in the buffer, but that changes nothing ...

int counter=0;

while(counter<1 || counter>22)
{
//cin.ignore();

cout << "How many players are in the game (not counting the dealer)? - ";
cin >> counter;

if (!isdigit(counter))
counter=0;

if (counter>22)
cout << "Error message 1";
if (counter<1)
cout << "Error message 2";
}

Thanks -

Luc
You never increment counter. Do this via counter++;
I think you are confused ... This is not a for loop, it is a while loop. As long as the user enters a number between 1-22 the loop will exit, and the program will continue. There is no need to increment as action is taken on what the user enters, not on a number of iterations ... Thanks though.
Really the program runs fine as long as a number is added, it is when a user enters an alpha that the infinite loop happens (sorry for not specifying that sooner).
It's happening because a character will convert to 0, which means that counter is then less than 1 which will continuously put out Error message 2 because the parameters for your while loop keeps looking at the counter. You need to change the parameters for your while loop.
OK, in case anyone else runs across this problem ...

The while loop is fine obviously (it does what it should). The issue is in the isdigit/isalpha, which SHOULD return an int (0 or some other) and then you should be able to act on that. For some reason however, it seems to leave a return or 0 in the buffer (not just returning 0 to the point of use/analysis - my best guess) so you can never cin again to change the entry. Thus you need to:

char entry[80];
int counter=0;

while(counter<1 || counter>22)
{
cout << "How many players are in the game (not counting the dealer)? - ";
cin >> entry;

if (checkForInt(entry)==false)
cout << "That is not a valid entry." << endl;
else
counter = atoi(entry);


if (counter>22)
cout << "Error1" <<
"Please try again ...\n\n";
if (counter<1)
cout << "Error2" <<
"Please try again ...\n\n";
}

bool checkForInt(const char *str)
{
// is the string empty?
if (strlen(str) == 0)
return false;

//else
while (*str!='\0')
{
if (*str<'0' || *str>'9')
return false; // not a digit
str++;//move to next char
}

return true;//if all digits
}
Topic archived. No new replies allowed.