检查功能如果输入为int或浮动PT次数? [英] Function to check if input is int or floating pt number?

查看:174
本文介绍了检查功能如果输入为int或浮动PT次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C函数来检查如果输入的是int,long int类型或浮动?我知道C有一个ISDIGIT()函数,我可以如下创建IsNumeric函数:

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:

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

但我不知道如何创造条件,采取浮动PT次数(作为字符串)和输出TRUE / ​​FALSE值的函数。

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

谢谢,
马库斯

Thanks, Marcus

推荐答案

这应该这样做。这将字符串转换为浮点使用的strtod 并检查是否有之后任何更多的投入。

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;
}

浮动 INT s是棘手的区分。一个正则表达式是一条路可走,但我们可以只检查浮动字符:

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.

这篇关于检查功能如果输入为int或浮动PT次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆