1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <stdio.h>
void ignore_rest_of_line()
{
char ch;
while ( scanf( "%c", &ch ) == 1 && ch != '\n' ) ;
}
int get_int( const char *prompt, int minv, int maxv )
{
printf( "%s? an integer in [%d,%d], immediately followed by a new line: ",
prompt, minv, maxv ) ;
int number ;
char nextc ;
int result = scanf( "%d%c", &number, &nextc ) ;
if( result == 2 && nextc == '\n' )
{
if( number < minv ) printf( "the value %d is too small. try again\n", number ) ;
else if( number > maxv ) printf( "the value %d is too large. try again\n", number ) ;
else return number ; // valid input,; return it
}
// else if( result == EOF ) { /* input failure on stdin */ }
else
{
puts( "invalid input. try again." ) ;
ignore_rest_of_line() ;
}
return get_int( prompt, minv, maxv ) ; // try again
}
int main()
{
const int year = get_int( "year of your birth", 1900, 2019 ) ;
printf( "the year of your birth is %d\n", year ) ;
}
|