Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

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

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 can create an isnumeric function as follows:

int isnumeric( char *str )
{
    while(*str){
        if(!isdigit(*str))
            return 0;   
        str++;
    }
    return 1;
}

But I was wondering how to create a function that would take a floating point number (as a string) and output a TRUE/FALSE value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...