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.
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()
}