I'm trying to validate the input and only accept numeric entries at the set length. I'm getting weird behaviour if characters are inputed though. The while loop seems to execute two rounds per character. Can anyone see what the problem might be.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define LENGTH 4
#define ZERO 48
#define NINE 57
int main()
{
int stringLength = LENGTH + 4;
char string[stringLength];
unsigned int n, i = 0;
bool valid;
do{
valid = true;
printf("Enter a %d digit number: ", LENGTH);
for(i = 0; i < LENGTH; i++){
string[i] = getchar();
if(string[i] < ZERO || string[i] > NINE){
valid = false;
break;
}
}
}while(!valid);
string[i] = 0;
n = strtol(string, NULL, 0);
printf("%d\n", n);
return 0;
}
Also, are there some good guidlines to be found somewhere for making generic safe input functions?