This function works fine as long as the user inputs integers only, however if the user inputs characters when asked their age, the function goes into an infinite loop. Is there a way I can make the function only accept integers? while (age != int) doesn't work :P
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void getage(void)
{
int age;
cout << "How old are you, if I may ask?" << endl;
do
{
cin >> age;
if (age < 0)
cout << "You can't be younger than zero! Try again." << endl;
elseif (age > 100)
cout << "That would be too old to play this game! Put in your real age." << endl;
else
cout << "Now tell me your real age wise guy." << endl;
} while (age < 0 || age > 100);
cout << age << "! Is that right?";
}
while( !( std::cin >> age ) || ( cin.get(c) && c != '\n' ) )
//if it fails to read or stuff left in buffer (excluding the trailing newline)
{
std::cout << "invalid input, please try another: ";
std::cin.clear(); //clear the bufer
std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' );
//ignore anything that might be left in the buffer
}