int check

Hello guys, I need to check whether the cin input is an integer or not. (I mean integer not digit.)
Part of my code is like;

1
2
3
4
5
6
 int Size;
 cin >> size;
 while(Size%2 != 1)
	{
		Error(Size);
	}


When user enters some alphabetic characters or a string the program goes for an infinite loop. How can I prevent that?
Last edited on
There are numerous ways to do this but here is one method:
Loop while 1) it fails to read into an integer or 2) there is anything left in the buffer other than the newline left from std::cin >>

1
2
3
4
5
6
7
8
9
10
11
char c;
std::cout << "Please enter an integer: ";
while( !(std::cin >> Size) || ( std::cin.get(c) && c != '\n' )
{
    std::cin.clear(); //clear error flags
    std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore anything left
    //std::cin.ignore( 1024 , '\n' ) or anything large will work too
    std::cout << "Invalid input. Please try again(integer only): ";
}

std::cout << "The valid integer entered was: " << Size << std::endl;

http://ideone.com/0TfnZI
Topic archived. No new replies allowed.