This code was originally for an assignment. I met the requirements of the assignment but wish to expand the code to further check for valid input. I am quite new at this but trying to learn...
Anyway, the problem is this. I can check if the float is non-negative with a simple loop as such:
int main(void)
{
//initialize variable
float fDollars=0.00;
//prompt for and accept input
printf("Please enter a dollar amount: ");
scanf("%f", &fDollars);
//check user response as valid
while (fDollars <= 0.00)
{
printf("\nYou entered an invalid response.");
printf("\nPlease enter a postive amount: ");
scanf("%f", &fDollars);
} //end while
return 0;
} //end main
I can alternatively check to see if the input is not a character with the following:
//Loop until user inputs a valid dollar amount
while (scanf("%f", &fDollars) != 1)
{
while (getchar() != '\n');
printf ("Please enter a dollar amount: ");
} //End loop
printf ("You entered %.2f\n", fDollars);
However, I am not able to check both with any success.
I have read that scanf is not preferred but I am not sure what else to use.
Also, would it be better to accept the float as a string and then convert to a float? I think it would be for validation but do not even know where to begin on that one.
If anyone is interested in looking at the entire program, it is attached. I know I still have some other things to work on with it to make it more robust and user-proof. However, I am using this to learn.
Thanks.