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.");
		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.");
		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.");
		{	dPrice = atof(sPrice);
			if(dPrice == 0.0)
			{	printf("Invalid price.");
			{	dPrice = (dPrice*100)+0.05;		/*convert to cents before storing*/
				price = (int)dPrice;
		/*end of price validation*/

Recommended Answers

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?
thanks for the reply...

use strtod() instead of atof(). Read the description of that function carefully and you will see how you can use it to verify that the string contains only numeric digits plus dot and dash. Otherwise you can just parse the string yourself to validate it.

Read a string fgets()
set flag to TRUE
For i=0 to string length
    if string(i) != digit nor dot set flag to FALSE
end for
if flag = FALSE number was not entered
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.