Since 'scanf()' is really ugly dealing with inputs , i decided to write a function that will hopefully be perfect when asking for numbers from the user.
The function is called 'getl()' (get long), it has 3 arguments and need no extra header files to be included. First and Second argument let you specify the range of max\min integer allowed to be input. Third takes a costumized message that will be displayed in these cases :
- When the user immdiatly hit <Enter> without entering anything.
- When the input doesn't belong to the range you specified.
- When the user enters an invalid input i.e : a mix of numbers and letters.
- When the user enters a real number (i.e: 4.5)
The function will keep displaying your custom message and asking for another input untill you enter a valid one.
here is the code :
Let me know what you guys think about it. And if it has any weak points , feel free to modify or add to it to make it even better.
long getl(long, long , char *);
printf("Please enter a number :\n");
number = getl(0,500,"Invalid Input.\n\nPlease enter a number :");
printf("You've entered %d\n\n", number);
long getl(long min_int, long max_int, char *message)
if( fgets(input, sizeof(input), stdin) == NULL )
printf("\nCould not read from stream\n");
result = strtol(input, &p, 10);
if(result <= max_int && result >= min_int && input!='\n' && ( *p == '\0' || *p == '\n' ))
p.s : i know nothing is perfect , i use perfect as in "as good as possible".