The function is used to validate the input. It prompts the user for a numeric value (great or equal to 0 ) until it meets the coditions. if any character input precedes or follows the number, the input is to be treated as invalid.The required output is:
Enter a positive numeric number: -500
Error! Please enter a positive number:45abc
Error! Please enter a number:abc45
Error! Please enter a number:abc45abc
Error! Please enter a number:1800
Well, it seems easy:
#include <stdio.h>
main() {
int ret=0;
double num;
printf("Enter a positive number:");
ret = scanf("%.2lf",&num);
while (num <0 ) {
if (ret!=1){
while(getchar()!= '\n');
printf("Error!Please enter a number:");
}
else{
printf("Error!Please enter a positive number:");
}
ret = scanf("%.2lf",&num);
}
}
however, my code keeps put out Error!Please enter a number: regardless types of input. Any advice?
I think you’ll have problems doing the validation you want using just scanf(). You’ll do better to first scan in a string and then convert it to a numeric. But scanf() is dangerous for scanning in char strings, since its input length is not limited and you have to provide it a pointer to a finite-length input buffer. Better to use fgets(), which allows you to limit the input buffer length.