I am using a switch statement as a menu. If I enter a non-integer value as my choice, I expect the error message , "Invalid entry", to display but instead the output keeps running. Please help me fix this.
#include <iostream>
#include <cctype>
int read_int( constchar* prompt, int minv, int maxv )
{
int value ;
char delimiter ;
std::cout << prompt << " (integer in [" << minv << ',' << maxv << "])? " ;
// try to read an int, immediately followed by a white space character
if( std::cin >> value && std::cin.get(delimiter) && std::isspace(delimiter) )
{
// the user did enter an integer value
// if value is in with range, return it
if( value >= minv && value <= maxv ) return value ;
// if not, inform the user of the error and try again
std::cout << value << " is out of range\n" ;
}
else
{
// the user did not enter an integer value
// inform the user of the error
std::cout << "input is not an integer\n" ;
// clean up
std::cin.clear() ; // clear failed state if any
std::cin.ignore( 1000, '\n' ) ; // throw away any junk left in the input buffer
// and try again
}
return read_int( prompt, minv, maxv ) ; // try again
}
int main()
{
constint n = read_int( "please enter a number", 1, 6 ) ;
std::cout << "you entered the number " << n << '\n' ;
}