In my program I want to work with numbers. And I would like to loop the program if the user enters not a number. That is, if "f", "12f", "120941s", "123a13" is entered, it should display an error and ask you to enter it again. I set a condition, because it is also important. But I also need to get another number without conditions, as long as it is just not a symbol.
I put a loop, but it will give an error in the case of the first entered character, but if I enter "22ff", it will write 22 to me in a variable, and ff to the next variable (I need to get several variables with numbers) and create an error. Because of this, I'm still trying to clean up stdin so that there is no stream sent to the next variable
How can i do this? Am I better off checking it as a string? Looping is also important to me, because I want to move on to work, not end the program. I will be glad to every advice! Thank you!
do {
bool valid;
printf("Enter number x(float) ");
while(!scanf(" %f", &x)) {
printf("x must be number!\nPlease, enter number! ");
fflush(stdin); }
if (x < 0) printf("\nThe number a must be positive. Try again\n");
else valid = 0
} while (valid)
CodePudding user response:
Here is a function that will validate input, within a certain range, and with no trailing rubbish. It uses fgets
and it is easy to just dump a bad input and repeat.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
double getdouble(double minval, double maxval)
{
char buffer[64]; // generous
char *endptr; // pointer to the next character
double inval; // result
while(1) {
printf("Enter a double value between %f and %f: ", minval, maxval);
if(fgets(buffer, sizeof buffer, stdin) != NULL) {
inval = strtod(buffer, &endptr);
// check next character, and the range of the value
if(isspace(*endptr) && inval >= minval && inval <= maxval) {
break; // success
}
}
}
return inval;
}
int main(void)
{
printf("%f\n", getdouble(1.0, 2.0));
}
Program session:
Enter a double value between 1.000000 and 2.000000: 1.5t
Enter a double value between 1.000000 and 2.000000: 2.5
Enter a double value between 1.000000 and 2.000000: abc
Enter a double value between 1.000000 and 2.000000: 1.5
1.500000
Please note that I used double
not float
. Never use float
without a clear reason why you cannot use double
, the natural floating point type in C.