infinite while loop

my intension is to have an input that would not accept characters. But for some reason my while loop wont stop to let the try again. It just runs on....



cin>>answer;
while (!isdigit(answer))
{
cout<<"not a number,try again";
cin>>answer;
}
If answer is a char, this should work (almost) fine.
I have a feeling that 'answer' is an int, which can cause problems if you put in a char, and in that case you'll want to do something like this each time through:
1
2
3
4
5
if (cin.fail())
{
	cin.clear();
	cin.ignore(INT_MAX, '\n');
}
closed account (zb0S216C)
This works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int iAnswer( 0 );

while( true )
{
    std::cin.sync( );
    std::cin >> iAnswer;
    if( !std::cin.good( ) )
    {
        std::cin.clear( );
        std::cout << "That's not a number" << std::endl;              
    }

    else
        std::cout << "That's a number" << std::endl;
}

Wazzak
Last edited on
Topic archived. No new replies allowed.