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')
{ readRestOfLine();
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*/
(sPrice[0] == '.')) /*can't start with a point*/
{ 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*/