I am working on a simple project of C-Programming called "Election System". But i want to optimize it so the output will never be wrong. So for this i need this:-
How to write a program to ask the user for an input between 1-20 but it prints "invalid input" if user enters "any character or string or negative integers"?
And please explain your code while giving the answer it would be really appreciated.
So far i didn’t tried anything. I could not think of logic for character or string input
for negative number its easy.
>Solution :
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