So the gist of my problem is that I am getting the user to input a number between 1 and 30 inclusive and the program is meant to spit an error and re-prompt the user for input until valid input is received. I used a loop to get the input then check it against various cases using an if-else tree and exiting the loop once appropriate input is received. The case checking against whether or not the number is in that range works (or worked) perfectly fine however when I check to make sure that the user did not enter a character, string, or anything else instead of an integer, the whole thing pretty much blows up in my face and the loop seems to be acting weird. I was told at first it was an issue with not closing the input buffer so I added that fix and it led to an instance where despite the condition being met properly the first time, it would not jump back to the front of the loop to allow the input to be altered and instead would immediately jump to a branch and continually print that message on the order or thousands of times per second. Below is the code. The part that gets continually printed is the "if( isalpha(uNum) ){...". For this revision of my code, putting inputs above 30 and below 1 work just fine however throwing in something like "abc" continually prints the message for going over 30 (i.e. "Value must be at most 30..."). When I take out the statement to clear the buffer ( "while(getchar() != '\n');" ) the aforementioned messages is constantly spammed without end. Can somebody help me out with why that is and/or what I need to do to fix it? My code can be seen below:
int get_seed(void)
{
int uNum;
printf("Please enter an integer between 1 and 30:\n");
while(1) {
scanf("%d",&uNum);
while(getchar() != '\n');
if( isalpha(uNum) ){
printf("Your entry must start with a digit; try again\n");
}
else if( (uNum < 1) || (uNum > 30) ){
if(uNum<1){
printf("Value must be at least one; try again\n");
} else {
printf("Value must be at most 30; try again\n");
}
continue;
}
else
break;
}
return uNum;
}
At this point I am wondering if it would make more sense to simply change the "else break;" statement (which means the input was good) to have a compound condition of <=30 and >=1 so that a new else statement takes care of what the first if was supposed to do.
Aucun commentaire:
Enregistrer un commentaire