Boy, this darn thing is stumping me. I want to create a loop that verifies if a user has entered an int (and not some other data type). To do this, I get the first character of the user's input using fgets()
, and then I check if that character is a digit (that is the minimum part of my task for the code to break).
char input[2];
int main(){
printf("Please enter the minimum value the random number can be: ");
fgets(input, sizeof(input), stdin);
printf("%c", input[0]);
if(!isdigit(input[0])){
int escape = 0;
while(escape == 0)
printf("Try again: ");
fgets(input, sizeof(input), stdin); //This will now overwrite whatever was in 'input'
if (isdigit(input[0])) //Will keep looping back to the fgets(), asking for new input each time until you enter a number.
escape = 1;
flushInpt();
}
In the above code (assuming all the right libraries are #included), it should ask for input (which it does) then check if the first character of that input is a digit (which it does) and if it is not a digit it should enter a while
loop where it prints "Try again: " with a new fgets()
that waits for the user to put in new input. It stays inside that while
loop until they input a digit as the first char, at which point it breaks out of the loop (this is the part it does not do).
But whenever I input a non-digit the first time, it enters the while
loop as expected, but then infinitely prints "Try again: " over and over again without ever stopping at the getsf() statement to wait for new input? My question is why does it loop infinitely?
I have verified as well that the flushInpt() function is not the culprit, as the problem occurs whether that call is in the loop or not. In case you were wondering, flushInpt is just a basic loop function that walks through the input buffer and removes anything that might be there.
char ch;
void flushInpt(){
while ((ch = getchar()) != '\n' && ch != EOF)
continue;
}
You're missing curly braces:
while(escape == 0)
{ //<--
printf("Try again: ");
fgets(input, sizeof(input), stdin); //This will now overwrite whatever was in 'input'
if (isdigit(input[0])) //Will keep looping back to the fgets(), asking for new input each time until you enter a number.
escape = 1;
flushInpt();
} //<--
I guess this block is your while loop.