有没有在C函数来检查,如果输入是int,long int或float?我知道C有一个isdigit()函数,我可以创建一个isnumeric函数如下:
int isnumeric( char *str )
{
while(*str){
if(!isdigit(*str))
return 0;
str++;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
但我想知道如何创建一个将浮点数(作为字符串)并输出TRUE/FALSE值的函数.
wal*_*lyk 12
这应该做到这一点.它使用strtod将字符串转换为浮点数,并检查后面是否还有其他输入.
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;
}
Run Code Online (Sandbox Code Playgroud)
区分floats和ints是比较棘手的.正则表达式是一种方法,但我们可以检查浮动字符:
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
}
Run Code Online (Sandbox Code Playgroud)
当然,更简化的方法是将值的类型和值一起返回.
int isnumeric( char *str )
{
double d;
return sscanf(str, "%lf", &d);
}
Run Code Online (Sandbox Code Playgroud)