Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Quboid

macrumors 6502
Original poster
Oct 16, 2006
441
0
everywhere
Hey folks

I am trying to write a program for class (in c), and i would like it to validate that the user only introduces a number with a decimal point (a float, rational number). I am not sure if there is a function to do this or if i have to work out the logics my self, either way, i would really like some help with this. Thanks a lot.
 

mufflon

macrumors 6502
Sep 15, 2006
264
2
in c you can pretty much see a string of letters as a vector of chars which ends with NULL (the latter part is highly irrelevant for this assignment)

I see 2 alternatives here:

1) go through each separate char and look for a , or .

2) use modulus 12.8 % 1 = 0.8 - so if x % 1 isn't 0 you can pretty much sum it up as a non-integer...
 

lazydog

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
How about something like this:-


Code:
char* input_str ; // Initialised in some way to the user's input.
float v ;

if ( sscanf( input_str, " %f", &v ) == 1 && fmod( v, 1.0f ) != 0.0f )
… // a decimal number was entered

b e n
 

Spanky Deluxe

macrumors demi-god
Mar 17, 2005
5,285
1,789
London, UK
Hey folks

I am trying to write a program for class (in c), and i would like it to validate that the user only introduces a number with a decimal point (a float, rational number). I am not sure if there is a function to do this or if i have to work out the logics my self, either way, i would really like some help with this. Thanks a lot.

You could convert the input number to an integer, convert that back to a float and then compare that value to the original value. If its equal then the number's an integer. That's what I would do. There'll be more elegant solutions but that's quick and simple.
 

foo.c

macrumors newbie
Nov 29, 2006
11
0
char* end;
double d = strtod(input_str, &end);
if((end == input_str) || (*end != '\0'))
{
printf("Bad input!\n");
}

If you really require a decimal point in the input (why?), you could then just scan the input_str for a '.'.

(If you add any more requirements to the input, you might consider using a regular expression.)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.