PDA

View Full Version : Another trivial c quesiton.

Quboid
Feb 25, 2007, 04:49 PM
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
Feb 25, 2007, 05:38 PM
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
Feb 25, 2007, 06:20 PM

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
Feb 25, 2007, 06:28 PM
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
Mar 1, 2007, 12:25 AM
char* end;
double d = strtod(input_str, &end);
if((end == input_str) || (*end != '\0'))
{