Complexity seems to be my downfall.
My son asked what if the user wanted to know why they are being asked for input again instead of just a new cursor. So I added some error messages and a way to turn them on or off if desired.
Code:
/*
* File: inputnumber.c
* Author: jim
*
* Created on June 9, 2010, 11:09 AM
*/
/* *******************************************************
* Testbed for number input routines
*************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MIN -100
#define MAX 100
#define EXTRA 1
#define VERBOSE_ON 1
#define VERBOSE_OFF 0
#define CURSOR ">>>"
long int InputNumber(int min, int max, int verbose);
void ClearBuf(void);
int main(void){
long int number;
printf("Enter a number (%d to %d)\n",MIN,MAX);
number = InputNumber(MIN,MAX,VERBOSE_ON);
printf("The number you entered = %ld\n",number);
return 0;
}
long int InputNumber(int min, int max, int verbose){
int i;
char buffer[BUFSIZ];
char* pEnd;
long int input;
do{
// Making sure that buffer is empty when looped
// not sure if I need to do this
for (i = 0; i < sizeof buffer; i++){
buffer[i] = 0;
}
// Make sure that all the values are 0 when looped
errno = 0;
input = 0;
printf(CURSOR);
if (fgets( buffer,sizeof buffer ,stdin)!= NULL){
input = strtol(buffer,&pEnd,10);
if ( buffer[0] != '\n' && *pEnd == '\n' || *pEnd == '\0'){
// do something if successful stub
// not necessary but could be useful in some circumstances
}
else {
if ( input == 0 && buffer[0] == '\n'){
if (verbose == VERBOSE_ON) printf("You just hit return Please enter a number first!\n");
}
else if(input == 0 && *pEnd != '\n'){
if (verbose == VERBOSE_ON) printf("You entered letters not numbers!\n");
}
else
if (verbose == VERBOSE_ON) printf("You added %s",pEnd);
// This is to make it loops if there is extra data
// also when number to large reset input from junk
if(errno != ERANGE) errno = EXTRA;
if(errno == ERANGE) input = 0;
}
}
if (errno == ERANGE)
if (verbose == VERBOSE_ON) printf("The number is to large!\n",input);
if (input < min || input > max && errno != ERANGE)
if (verbose == VERBOSE_ON) printf("Your input %ld is out of range %d to %d\n",input,min,max);
}
while ( input < min || input > max ||errno == ERANGE || errno == EXTRA);
return input;
}