I am new to C and I am writing a "get_int" script. I am implementing a while loop to check the validty of the input. If it is not a valid input (not an integer) as checked by scanf(),then we reprompt the user for it. In the case I entered a number, it did print out the value I want. However, in the case I input a character or a string, it runs into a permanent loop of printing "x:" without lettting me check using scanf() the validity of the input.
My code runs as below:
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int x;
while (true)
{
printf("x: ");
if (scanf("%i", &x) == 1)
{
break;
}
}
printf("x: %i\n", x);
}
Sorry. I am kinda clueless here.