You can write something like the following
const unsigned int MIN = 1;
const unsigned int MAX = 20;
unsigned int value = 0;
do
{
printf( "Enter a value in the range [%u, %u]: ", MIN, MAX );
if (scanf( "%u", &value ) != 1 || value < MIN || MAX < value )
{
puts( "Invalid input." );
while ( getchar() != '\n' );
value = 0;
}
} while ( value < MIN || MAX < value );
If the user will enter an invalid number
if (scanf( "%u", &value ) != 1 || value < MIN || MAX < value )
then the inner while loop
while ( getchar() != '\n' );
skips invalid characters in the input buffer.
Here is a demonstration program.
#include <stdio.h>
int main( void )
{
const unsigned int MIN = 1;
const unsigned int MAX = 20;
unsigned int value = 0;
do
{
printf( "Enter a value in the range [%u, %u]: ", MIN, MAX );
if (scanf( "%u", &value ) != 1 || value < MIN || MAX < value )
{
puts( "Invalid input." );
while (getchar() != '\n');
value = 0;
}
} while (value < MIN || MAX < value);
printf( "value = %u\n", value );
}
The program output might look like
Enter a value in the range [1, 20]: Hello
Invalid input.
Enter a value in the range [1, 20]: 21
Invalid input.
Enter a value in the range [1, 20]: 20
value = 20
However the approach has one drawback. An input like that
20 A
will be correct because the call of scanf
successfully will read the number 20
from the input buffer.
Another and more reliable approach is to use standard functions fgets
and strtol
. But its implementation can be more complicated if you do not want to allow such input like
20 A