Function to check if input string is an integer or floating point number?

后端 未结 3 968
谎友^
谎友^ 2020-12-10 08:56

Is there a function in C to check if the input is an int, long int, or float? I know C has an isdigit() function, and I

3条回答
  •  死守一世寂寞
    2020-12-10 09:39

    If your goal is to find the data type a given string can fit in, you can do something like this:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    /* If a floating-point number is +/- F_EPS from an integer,
       consider it to be an integer */
    #define F_EPS 1e-7
    
    enum datatype {
        TYPE_INT,
        TYPE_LONG,
        TYPE_FLOAT,
        TYPE_DOUBLE,
        TYPE_INVALID
    };
    
    enum datatype findtype(const char *s)
    {
        char *eptr;
        double d;
        double diff;
    
        errno = 0;
    
        d = strtod(s, &eptr);
        if ((d == 0 && eptr == s) || errno == ERANGE)
            return TYPE_INVALID;
    
        diff = d - floor(d+0.5);
        if (d <= INT_MAX && d >= INT_MIN && diff <= F_EPS)
            return TYPE_INT;
    
        if (d <= LONG_MAX && d >= LONG_MIN && diff <= F_EPS)
            return TYPE_LONG;
    
        if ((d > 0 && (d > FLT_MAX || d < FLT_MIN))
                    || (d < 0 && (d < -FLT_MAX || d > -FLT_MIN)))
            return TYPE_FLOAT;
    
        return TYPE_DOUBLE;
    }
    

    The idea is that you read the number as a double, and then check to see if it is in the range for different types. You can change F_EPS above to control the tolerance.

提交回复
热议问题