c语言字符串不能是数字,C语言判断字符串是否为数字

这篇博客介绍了一个用C语言编写的函数is_number(),用于判断输入的字符串是否为数字,包括整数、十六进制整数和小数。函数通过跳过空白字符、处理正负号、识别数字和小数点来实现这一功能。博主还提供了一个测试程序验证了函数的正确性。
摘要由CSDN通过智能技术生成

判断一个字符串是否为数字, 听起来很简单,实现还是有点难度的。 最近写了一个,如下:

#define IS_BLANK(c) ((c) == ' ' || (c) == '\t')

#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')

#define IS_ALPHA(c) ( ((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') )

#define IS_HEX_DIGIT(c) (((c) >= 'A' && (c) <= 'F') || ((c) >= 'a' && (c) <= 'f'))

/* Whether string s is a number.

Returns 0 for non-number, 1 for integer, 2 for hex-integer, 3 for float */

int is_number(char * s)

{

int base = 10;

char *ptr;

int type = 0;

if (s==NULL) return 0;

ptr = s;

/* skip blank */

while (IS_BLANK(*ptr)) {

ptr++;

}

/* skip sign */

if (*ptr == '-' || *ptr == '+') {

ptr++;

}

/* first char should be digit or dot*/

if (IS_DIGIT(*ptr) || ptr[0]=='.') {

if (ptr[0]!='.') {

/* handle hex numbers */

if (ptr[0] == '0' && ptr[1] && (ptr[1] == 'x' || ptr[1] == 'X')) {

type = 2;

base = 16;

ptr += 2;

}

/* Skip any leading 0s */

while (*ptr == '0') {

ptr++;

}

/* Skip digit */

while (IS_DIGIT(*ptr) || (base == 16 && IS_HEX_DIGIT(*ptr))) {

ptr++;

}

}

/* Handle dot */

if (base == 10 && *ptr && ptr[0]=='.') {

type = 3;

ptr++;

}

/* Skip digit */

while (type==3 && base == 10 && IS_DIGIT(*ptr)) {

ptr++;

}

/* if end with 0, it is number */

if (*ptr==0)

return (type>0) ? type : 1;

else

type = 0;

}

return type;

}

is_number(char *) 函数判断字符串是否为数字。如果不是,返回0。如果是整数,返回1。如果是十六进制整数,返回2. 如果是小数,返回3.

编一个测试程序:

#include

#include

int main(int argc, char**argv)

{

assert( is_number(NULL) ==0 );

assert( is_number("") ==0 );

assert( is_number("9a") ==0 );

assert( is_number("908") ==1 );

assert( is_number("-908") ==1 );

assert( is_number("+09") ==1 );

assert( is_number("-+9") ==0 );

assert( is_number(" 007") ==1 );

assert( is_number("0x9a8F") ==2 );

assert( is_number("-0xAB") ==2 );

assert( is_number("-9.380") ==3 );

assert( is_number("-0xFF.3") ==0 );

printf("test OK\n");

}

运行, "test OK"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值