-
here..
I worked my butt out (to improve it) and I came up with this :
PHP Code:
int checknumber(char array[20])
{
int i;
int minuscount = 0;
int pointcount = 0;
int bad = 0;
for (i=0; array[i]; i++)
{
if ( array[i] == 45)
{
minuscount++;
}
if ( array[i] == 46)
{
pointcount++;
}
if( array[0] == NULL || array[i] < 45 || array[i] == 47 || array[i] > 57 )
{
bad = 1;
}
if(i>0 && array[i] == 45)
{
bad = 1;
}
}
if (minuscount > 1 || pointcount > 1)
{
bad = 1;
}
return bad;
}
The function returns 0 for no errors and 1 if there are errors
LIMITATIONS :
1) . is valid
2) -. is valid
3) x. is valid (where x is a number)
4) array can't have more than 20 elements. increase this if you want.
Also, if you're using cin, ' ' (space) will give strange problems.
I hope this will be of some use to you. :)
-
thanks it helped alot. i modified it a little thouhg but it helped a lot!
-
There is a group of istream methods; good(), fail(), clear(); that can do input error checking for you, too. You should look up the syntax, but I think it something like this:
Code:
cout << "input a floating point number;
float num;
cin >> num;
if(cin.fail())//or if(!cin.good())
{
cout << "input error, not a valid floating point number" << endl;
cin.clear();
}
else
cout << num << endl;
-
Don't count on good() catching bad input beyond the first digit.
Where it works nicely is in a simple console-based program with a menu, for example, where a single digit is expected as input. However, as long as the first character read into the stream is a digit, you can put in anything after that and the compiler will accept the input as valid.
As you might discern, it makes no distinction between ints and floats. I know there are a lot of folks that wish that determining the validity of a float were that simple. :)
-Skipper