Another trivial c quesiton.

Discussion in 'Mac Programming' started by Quboid, Feb 25, 2007.

  1. Quboid macrumors 6502

    Oct 16, 2006
    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.
  2. mufflon macrumors 6502

    Sep 15, 2006
    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...
  3. lazydog macrumors 6502a

    Sep 3, 2005
    Cramlington, UK
    How about something like this:-

    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
  4. Spanky Deluxe macrumors 601

    Spanky Deluxe

    Mar 17, 2005
    London, UK
    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.
  5. foo.c macrumors newbie

    Nov 29, 2006
    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.)

Share This Page