Runtime error in console

for example
int num;
std::cout<<"Please enter a number: ";
std::cin>>num;

when this code is compile and run, it asks the user to input a number, if mistakenly a character or string is inputted, the console begins an endless loop. How do I check this error. Thanks in advance.
1
2
3
4
5
6
if(!std::cin) //check if failbit is set
{
    std::cin.clear(); //clear error flags
    std::cin.ignore(1024, '\n'); //ignore anything left in the buffer
    //you may replace 1024 with any decent size number or even std::numeric_limits<std::streamsize>::max()
}



Or better yet something like

1
2
3
4
5
6
7
while(std::cout << "Please enter a number: " && !(std::cin >> num))
{
    std::cerr << "Error - Invalid number entered." << std::endl;
    std::cin.clear(); //clear error flags
    std::cin.ignore(1024, '\n'); //ignore anything left in the buffer
    //you may replace 1024 with any decent size number or even std::numeric_limits<std::streamsize>::max()
}



Here is more information on operator ! http://www.cplusplus.com/reference/ios/ios/operator_not/
Last edited on
Yeah, the both worked. Thanks for your help @giblit
Topic archived. No new replies allowed.