finding the datatype of user input

does anyone know of a way to check the datatype of a users input to see whether it is an integer or not

smtraber


Answer this question

finding the datatype of user input

  • Reg Bust

    User input to what

    User input is usually a stream of characters. This stream of characters might be convertible to other data type inside your program. I.E. So a stream of characters entirely consisting of characters in the range from 0x30 up to 0x39 might be converted to an integer if there is no overflow.

    So to check what the users input is, you have to parse it and check it and make a decision what type it might be.

  • brikshoe

    I agree w/ Martin.  There's no hard and fast rule here: you have to determine the acceptable format and walk the characters to decide whether the string is of that format.  Is "10Z" = 10 or is it invalid input  

    Here's a snipplet, which is rather crude and matches:

    digit anything
    - digit anything
    . digit anything
    -.digit anything

    In other words: is this string convertable to a float  (This is a copy/paste of my code: you can modify it for integers only by removing matches against '.'). 

    bool
    IsNumeric( const char *ch )
    {
       assert( ch != 0 );
       return isdigit(*ch) ||
           (((*ch == '.') || (*ch == '-')) && isdigit(*(ch+1))) ||
           ((*ch == '-') && (*(ch+1) == '.') && isdigit(*(ch+2)));
    }

    This corresponds to the regex ([0-9] | [\.-][0-9] | -\.[0-9]).*  If you want to be more strict (e.g. reject "10Z"), then you'll need to walk all your characters, accepting each as appropriate.


  • Chrisjune

    Shell lightweight api (if it is not renamed)

    32-bit int: StrToIntEx()
    http://msdn.microsoft.com/library/default.asp url=/library/en-us/shellcc/platform/shell/reference/shlwapi/string/strtointex.asp

    64-bit int: StrToInt64Ex()
    http://msdn.microsoft.com/library/default.asp url=/library/en-us/shellcc/platform/shell/reference/shlwapi/string/strtoint64ex.asp

    #include <shlwapi.h>
    #pragma comment (lib, "shlwapi")

    Lean on the OS, they have worked on it.
    Don't reinvent the wheel.

  • finding the datatype of user input