Skip to content

Instantly share code, notes, and snippets.

@Poolitzer
Created October 21, 2021 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Poolitzer/d1e770a3a04601f90e2b1a8b3ff87b6b to your computer and use it in GitHub Desktop.
Save Poolitzer/d1e770a3a04601f90e2b1a8b3ff87b6b to your computer and use it in GitHub Desktop.
scanf_s with validation
// this while loop is active as long as the user didn't input anything or
// their input is out of range
while (validation == 0) {
validation = scanf_s("%d", &day);
// this if is true when either the input is wrong (no number given)
// or when the number is too low/high
if (validation != 1 || day < 1 || day > 31) {
// if validation is 0, the input buffer exists, so I DESTROY it
while ((c = getchar()) != '\n' && c != EOF);
printf("\nSorry, this was the wrong input. You need to give an \
integer between 1 and 31. Try again: ");
// validation could be one, and then the while loop exists, so we
// set it to 0. Happens when day is too high or low
validation = 0;
}
}
// reset validation so we can reuse the while loop
validation = 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment