hey guys heres a portion of my code, im trying to validate a users input of price and then convert it to cents before doing some other calculations.
Im having problems with my validation still somehow allows letters if they are not the first digit entered.
For example, a2 is invalid, whereas 2a is valid.
I've tried using atoi and isdigit as well as I have searched it up on google, but those dont work either, they dont return me a zero as I am expecting when a letter is entered.
Any help is much appreciated...

``````/*Price Validation*/
if(sPrice[strlen(sPrice)-1] != '\n')
printf("Invalid price, maximum is RM 9999.99.");
break;
}
if(sPrice[0] == '\n')
{   break;
}
if(sPrice[0] == '0' && sPrice[1] == '\n')
{	price = 0;
}
else if((sPrice[0] == '0' && sPrice[1] != '\n') ||	/*can't start with a zero*/
(atof(sPrice) == 0.0) ||	/*no letters*/
{	printf("Invalid price.");
break;
}
else if(strlen(sPrice) != strcspn(sPrice, point) &&	(strlen(sPrice) - strcspn(sPrice, point)) != 4)		/*must have 2 decimal digits or none at all*/
{	printf("Invalid price.");
break;
}
else
{	dPrice = atof(sPrice);
if(dPrice == 0.0)
{	printf("Invalid price.");
}
else
{	dPrice = (dPrice*100)+0.05;		/*convert to cents before storing*/
price = (int)dPrice;
}
}
/*end of price validation*/``````

## All 7 Replies

Did you find any error?

no errors... it simply allows the value to go thru, and takes 2a for example, as a 2.00

that's true -- atof("2a") is 2.00. I have no idea what the 'a' is for, but atof() stops converting at the first character that is not a digit or '.' or '-'.

The 2a is just an example of my input that is not supposed to be allowed by the program... but is...
if atof stops converting at the first non digit, dot or dash, then how do i go about validating the price?
``````Read a string fgets()