//flex table opened by JP

Click to See Complete Forum and Search --> : Validating input in C++


nothing
01-11-2004, 08:35 PM
bool valid_wage(string wage)
{
if(wage.length() == 0)
return false;

else {

for(int i = 0; i < wage.length(); i++) {

if(!isdigit(wage[i]))
return false;
}
}

return true;
}


This function won't let anything but a number be accepted as valid input, but there is a serious problem with it.

8.50, for example, is a valid number, but the function I wrote will not accept it as valid input. I have no ideia how to fix this. Can somebody help? Thank you. :t

bassman
01-11-2004, 08:55 PM
I'm not into C++ but I'm pretty sure that that's a problem related to the isdigit function as it may only be testing integers. If it error on a float/double, IMO it only tests integers. Did you make that function or is it prebuilt?

nothing
01-11-2004, 08:59 PM
It's prebuilt.

fishybawb
01-11-2004, 09:00 PM
Originally posted by nothing
This function won't let anything but a number be accepted as valid input, but there is a serious problem with it.


Bassman's right.
It won't allow float (decimal point) numbers - the for loop goes by the length of the input, but it only checks individual digits via the array index ie. variable[index]. For example, if you input the number 1.5, your for loop does something like this:

is 1 a digit -> yes, so continue
is . a digit -> no, so return false

It won't even reach the 5 part of the number.

bassman
01-11-2004, 09:06 PM
Try this; if isdigit returns false, use iswdigit (tests decimal numbers) to check if it's a valid number. If they both return false...there you go :)

cuelebre
01-11-2004, 09:16 PM
I really don't remember from the top of my head but, can you change the type of variable????

If so define it as "Float" or even "Double", That will alloud to validate the decimal point.

Bone Collector
01-11-2004, 09:42 PM
try it like this:


bool valid_wage(string wage)
{
if(wage.length() == 0)
return false;

else {

for(int i = 0; i < wage.length(); i++) {
if(wage[i]!='.')
if(!isdigit(wage[i]))
return false;
}
}

return true;
}

nothing
01-11-2004, 10:42 PM
That was really smart. Thank you :D

Bone Collector
01-12-2004, 06:44 PM
oops i forgot that you should probably check if there is more than one dot then return false because string like this "123.456.789" is not valid, right?

nothing
01-12-2004, 08:18 PM
A string like that would be a invalid string.

nothing
01-12-2004, 08:33 PM
bool valid_salary(string salary)
{
int dot_counter = 0;

if(salary.length() == 0)
return false;

else {

for(int i = 0; i < salary.length(); i++) {

if(salary[i] != '.') {

if(!isdigit(salary[i]))
return false;
}

else {

dot_counter++;

if(dot_counter > 1)
return false;
}
}
}

return true;
}


What do you think?

Bone Collector
01-13-2004, 10:19 AM
that should do it



if you wan't more compact code :) then:
dot_counter++;

if(dot_counter > 1)
return false;

replace with this
if(++dot_counter > 1)
return false;

:t