I am trying validate the user input. In case of an invalid input i am trying to ask the user to reinsert a correct numeric(double) value.
The program is not working, its going to an infinite loop.
Could you please give me any suggestion how can i do this ? Thanks.!!
int main() {
double t; /* Input from user */
int check;
check = 0;
/* This loop is use to validate the user input. *
* For example: If the user insert a character value "x". *
* i am trying to ask the user to insert a valid numeric value. */
while (check == 0)
{
printf("Insert the value: ");
if (scanf(" %lf", &t) == 1) {
check = 1; /* Everythink okay. No loop needed */
}
else
{
printf("Failed to read double. ");
check = 0; /* loop aganin to read the value */
fflush( stdout );
}
}
return 0;
}
expected results:
$ ./a.out
Insert the value: X
Failed to read double.
Insert the value: 5
actual results :
$ ./a.out
Insert the value: X
Insert the value: Failed to read double. Insert the value: Failed to read double. ( loop )...
if i entered an invalid character the program goes to an infinite loop... if i entered an invalid character the program goes to an infinite loop
OP's code is simply re-attempting to convert the same failed data endlessly.
When scanf(" %lf", &t) == 0
, non-numeric input remains in stdin
and needs to be removed. @Eugene Sh..
int conversion_count = 0;
while (conversion_count == 0) {
printf("Insert the value: ");
// Note: lead space not needed. "%lf" itself consumes leading space.
// if (scanf(" %lf", &t) == 1) {
conversion_count = scanf("%lf", &t);
// conversion_count is 1, 0 or EOF
if (conversion_count == 0) {
printf("Failed to read double.\n");
fflush(stdout);
int ch;
// consume and discard characters until the end of the line.
while ( ((ch = getchar()) != '\n') && (ch != EOF)) {
;
}
if (ch == EOF) {
break;
}
}
}
if (conversion_count == 1) {
printf("Read %g\n", t);
} else {
printf("End-of-file or input error\n");
}