I was going over number input in the FAQ here. I am about half done reading it and wanted to try out some of the early examples both good and bad to understand what is exactly going on. Here is a function I made. I added a min and max to limit the size of the number.
The call looks like this:
Code:printf("Enter a number (0-20)\n");
number = UserInput(MIN_NUMBER, MAX_NUMBER);
Code:int UserInput(int min, int max){
int input;
input = 0;
printf(CURSOR);
while (scanf("%d",&input) != 1 || input < min || input > max){
while (getchar() != '\n');
printf(CURSOR);
}
// while (getchar() != '\n'); <<<--- Should I put this here??
return input;
}
My question is two fold. First, shouldn't I clear the stdin before leaving this function. From what I can tell it still leaves junk in the buffer.
Two what would happen if the user exceeds the buffer? I tried it and seems the function works fine no matter how large a number is entered.