Walker Walker - 2 months ago 8
C Question

Entering while loop repeatedly before stopping at getchar()

I'm writing a simple C program in which I want to validate my user's input for integers from 1-9.

The logic for my code seems fine but for some reason if I type "lll" for my input (or any other random input not between 1-9), it will show the error message inside the while loop a couple of times before actually stopping at the getchar() once again.

/**
* Validate user input and reprompt if invalid
* @return input - Users valid input
*/
int validateUserInput() {
int firstInput = getchar() - 48;
int secondInput = getchar();

while(secondInput != 10 || firstInput >= 10 || firstInput <= 0 ){
printf("Invalid Input. Please try again. \nEnter a number between (1-9): ");

firstInput = getchar() - 48;
secondInput = getchar();
}

return firstInput;
}


The logic is that:


  • Invalid Input - If the second input != 10 which means that the second char is something other than the enter key.

  • Invalid Input - If the first char subtracted 48 is higher than 9 or less than 1 then it's too high.



The logic seems fine to me but here's some output when I enter random characters:

Enter a number between 1-9: lllll
Invalid Input. Please try again.
Enter a number between 1-9: Invalid Input. Please try again.
Enter a number between 1-9: Invalid Input. Please try again.
Enter a number between 1-9: Invalid Input. Please try again.
Enter a number between 1-9: Invalid Input. Please try again.
Enter a number between 1-9: Invalid Input. Please try again.
Enter a number between 1-9:


Why does it repeat that message so many times before actually letting me enter input again? This is all that's wrong with my program.

usr usr
Answer

Your logic is fine. But the invalid characters you input still remain in the input buffer. So, the subsequent calls to getchar() read them.

Whenever you hit an invalid input, you want to ignore them all. You can read them out using a loop like this:

  while(secondInput != 10 || firstInput >= 10 || firstInput <= 0 ){
     printf("Invalid Input. Please try again. \nEnter a number between (1-9): ");
     int i;
     while((i=getchar()) != '\n' && i != EOF);
     ...

Having said that it's generally hard to use getchar() and scanf() family functions to correctly read interactive input and do error checking. A better way would be to read lines (such as fgets()) and parse/error check them.

Comments