Testing a string as a valid float

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 666 Views - Last Post: 03 April 2013 - 01:02 PM Rate Topic: -----

#1 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Testing a string as a valid float

Posted 03 April 2013 - 11:53 AM

I need to take a char array, and test it to see if it's valid for conversion to a float.

My professor told us to use isDigit, but his logic is flawed because the decimal point is not a digit.

I know i have to test for more than one decimal.. but I'm having trouble with the decimal/isDigit test.

Should I remove the decimal? I don't know how... Here is what I am thinking.. this is just logic at this point since I started my program from scratch and haven't written my function yet.

1. Get string
2. Loop through chars with a decimal accumulator
3. If >2 decimal, false

then...
?loop again, I tried something like
(if isDigit[str[x] && str[x] != '.')

but it always threw a false.

Is This A Good Question/Topic? 0
  • +

Replies To: Testing a string as a valid float

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,656
  • Joined: 02-June 10

Re: Testing a string as a valid float

Posted 03 April 2013 - 11:59 AM

How about the logic

if (IsDigit or '.')

Hint: && is and. || is or.
Was This Post Helpful? 0
  • +
  • -

#3 jimblumberg  Icon User is online

  • member icon


Reputation: 3991
  • View blog
  • Posts: 12,315
  • Joined: 25-December 09

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:10 PM

Hint: Try to use positive logic whenever possible. Negative logic can be confusing when you combine them.

Jim
Was This Post Helpful? 0
  • +
  • -

#4 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:11 PM

Does positive logic mean you are testing for true?
Was This Post Helpful? 0
  • +
  • -

#5 jimblumberg  Icon User is online

  • member icon


Reputation: 3991
  • View blog
  • Posts: 12,315
  • Joined: 25-December 09

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:12 PM

Positively.

Edit: In other words try not to use the negation operator whenever possible.

if(isDigit(str[x]) ||  str[x] == '.')



Jim

This post has been edited by jimblumberg: 03 April 2013 - 12:16 PM

Was This Post Helpful? 0
  • +
  • -

#6 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,694
  • Joined: 19-March 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:16 PM

View Postsynlight, on 03 April 2013 - 01:53 PM, said:

I need to take a char array, and test it to see if it's valid for conversion to a float.

My professor told us to use isDigit, but his logic is flawed because the decimal point is not a digit.

I know i have to test for more than one decimal.. but I'm having trouble with the decimal/isDigit test.

Should I remove the decimal? I don't know how... Here is what I am thinking.. this is just logic at this point since I started my program from scratch and haven't written my function yet.

1. Get string
2. Loop through chars with a decimal accumulator
3. If >2 decimal, false

then...
?loop again, I tried something like
(if isDigit[str[x] && str[x] != '.')

but it always threw a false.



Don't loop through twice! Start a counter at zero. If you see a '.', check if that counter is greater than zero. If so, return false, otherwise, increment the counter.

You might also want to allow for negative numbers.
Was This Post Helpful? 0
  • +
  • -

#7 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:20 PM

Okay I just pounded this out very quickly..

double getBalance()
{
	char testBal[40];
	double balance = 0.00;
	bool floatTest = false;

	getString("\nPlease enter the balance due:", testBal, 40);

	floatTest = validFloat(testBal);

	if(floatTest)
		atof(testBal);

	while(!floatTest)
	{
		getString("\nInvalid balance due, please try again:", testBal, 40);
	}

	return balance;

}//END GETBALANCE


/*********************************
* Test For Valid Float *
*********************************/
bool validFloat(char testFloat[])
{
	bool isValid = false;
	int decimal = 0;

	for (int x = 0; x < strlen(testFloat); x++)
	{	
		if (testFloat[x] == '.')
			decimal++;
		
	}
	if (decimal > 1)
		isValid = false;
	else
	{
		for (int x = 0; x < strlen(testFloat); x++)
		{
			if (isdigit(testFloat[x] || testFloat[x] == '.'))
				isValid = true;
		}
	}
	return isValid;
}//END VALID


It is always returning false.
I need a logic meter LOL.
Was This Post Helpful? 0
  • +
  • -

#8 jimblumberg  Icon User is online

  • member icon


Reputation: 3991
  • View blog
  • Posts: 12,315
  • Joined: 25-December 09

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:32 PM

Look closely at this line:

            if (isdigit(testFloat[x] || testFloat[x] == '.'))

Why are you testing to see if testFloat[x] OR testFloat[x] == '.' is a digit?

Also your function will not tell you this "3.12a" is an invalid float even though it has an alpha character in it.

Jim

This post has been edited by jimblumberg: 03 April 2013 - 12:33 PM

Was This Post Helpful? 0
  • +
  • -

#9 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:34 PM

Okay.. as per Jim's direction I put it in one for loop:

bool validFloat(char testFloat[])
{
	bool isValid = false;
	int decimal = 0;

	for (int x = 0; x < strlen(testFloat); x++)
	{	
		if (testFloat[x] == '.')
			decimal++;
		if (isdigit(testFloat[x] || testFloat[x] == '.'))
				isValid = true;
	}
	if (decimal > 1)
		isValid = false;
	
	return isValid;


Nut my logic is flawed.. because I return true only if the last element meets the criteria, right?

View Postjimblumberg, on 03 April 2013 - 02:32 PM, said:

Look closely at this line:

            if (isdigit(testFloat[x] || testFloat[x] == '.'))

Why are you testing to see if testFloat[x] OR testFloat[x] == '.' is a digit?

Also your function will not tell you this "3.12a" is an invalid float even though it has an alpha character in it.

Jim


Well.. I was thinking as it looped through the array, it would test each element to see if it isdigit, or if it is a decimal.

EDIT.. do I need to enclose the isdigit condition in ()?

EDIT AGAIN.. IT WORKED !! The () worked!! Yay!!!

This post has been edited by synlight: 03 April 2013 - 12:36 PM

Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,656
  • Joined: 02-June 10

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:36 PM

Your loop from 19-23 of second block has a bug: YOu don't stop if you hit a false.
So it could all be false, so long as the last char is a period. At which point isValid becomes true.

There is no point continuing after a failure. Just return false at that point.

In the first block, you should move 14-15 in place of 07. That way the loop will keep asking AND THEN PROCESS. Have this loop at 14-15 with no processing after is pointless.

UPDATE: References to your original code. You updated as I was typing. <laugh>

This post has been edited by tlhIn`toq: 03 April 2013 - 12:38 PM

Was This Post Helpful? 1
  • +
  • -

#11 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,694
  • Joined: 19-March 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:37 PM

Once you've dealt with the decimal case, you know you're not dealing with a digit. You can use an else to avoid the second half in that case.

for (int x = 0; x < strlen(testFloat); x++)
{  
    if (testFloat[x] == '.')
    {
        decimal++;        
        if (decimal > 1) {
            return false;  // we're done at this point!
    }
  }
  else ...



you can use similar logic in the digits side: if you get there, and it's not a digit, then you can just return false.
Was This Post Helpful? 0
  • +
  • -

#12 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:45 PM

View PosttlhIn`toq, on 03 April 2013 - 02:36 PM, said:

Your loop from 19-23 of second block has a bug: YOu don't stop if you hit a false.
So it could all be false, so long as the last char is a period. At which point isValid becomes true.

There is no point continuing after a failure. Just return false at that point.

In the first block, you should move 14-15 in place of 07. That way the loop will keep asking AND THEN PROCESS. Have this loop at 14-15 with no processing after is pointless.

UPDATE: References to your original code. You updated as I was typing. <laugh>


Like this:
double getBalance()
{
	char testBal[40];
	double balance = 0.00;
	bool floatTest = false;

	while(!floatTest)
	{
		getString("\nPlease enter the balance due:", testBal, 40);
		floatTest = validFloat(testBal);
	}

	atof(testBal);
	
	return balance;

}//END GETBALANCE


How could I tell the user that they entered an invalid number?
Was This Post Helpful? 0
  • +
  • -

#13 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,694
  • Joined: 19-March 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:47 PM

if (!floatTest) { // go go gadget print statement }

This post has been edited by jon.kiparsky: 03 April 2013 - 12:48 PM

Was This Post Helpful? 1
  • +
  • -

#14 jimblumberg  Icon User is online

  • member icon


Reputation: 3991
  • View blog
  • Posts: 12,315
  • Joined: 25-December 09

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:47 PM

Quote

EDIT.. do I need to enclose the isdigit condition in ()?

Bingo! Yes!

if (isdigit(testFloat[x]) || testFloat[x] == '.')
                        ^




You should consider writing a test program to test this function. Something like:
int main()
{
   while(1)
   {
      char numberString[100];

      fgets(numberString,100, stdin);
      cout << (validFloat(numberString) ? "true" : "false") << endl; // Print true or false instead of zero or one.
   }

}



Then you can test many different sequences to see if you're handling them correctly. (your not).

Be sure to try many different things like "a.a", "12.2", "1a.2" etc. And you need to decide what you want to consider valid.



Jim
Was This Post Helpful? 1
  • +
  • -

#15 synlight  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 582
  • Joined: 14-September 11

Re: Testing a string as a valid float

Posted 03 April 2013 - 12:49 PM

[quote name='jimblumberg' date='03 April 2013 - 02:47 PM' timestamp='1365018441' post='1830948']

Quote

!


You should consider writing a test program to test this function. Something like:

   while(1)







Jim


What the heck is that?!? while(1)?!?

1 == true,, so is that while(true)?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2