Beginner Function Help Please

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;
		else if (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?";
			
}
You will have to use validations.

something like this:

1
2
3
4
5
6
7
8
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
}


http://ideone.com/CdE1DA
You might check out the following post:
http://www.cplusplus.com/forum/beginner/108849/#msg592118
Topic archived. No new replies allowed.