Created
October 21, 2021 07:23
-
-
Save Poolitzer/d1e770a3a04601f90e2b1a8b3ff87b6b to your computer and use it in GitHub Desktop.
scanf_s with validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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