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

后端 未结 3 950
谎友^
谎友^ 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

    This should do it. It converts the string to floating point using strtod and checks to see if there is any more input after it.

    int isfloat (const char *s)
    {
         char *ep = NULL;
         double f = strtod (s, &ep);
    
         if (!ep  ||  *ep)
             return false;  // has non-floating digits after number, if any
    
         return true;
    }
    

    To distinguish between floats and ints is trickier. A regex is one way to go, but we could just check for floating chars:

    int isfloat (const char *s)
    {
         char *ep = NULL;
         long i = strtol (s, &ep);
    
         if (!*ep)
             return false;  // it's an int
    
         if (*ep == 'e'  ||
             *ep == 'E'  ||
             *ep == '.')
             return true;
    
         return false;  // it not a float, but there's more stuff after it
    }
    

    Of course, a more streamlined way to do this is to return the type of the value and the value together.

提交回复
热议问题