c 字符转化数值

Posted on 2011-05-30 15:13 xsong 阅读(578) 评论(0)  编辑  收藏 所属分类: c
    c 提供了 atoi atof 等函数实现了字符串转化数值的函数。使用方法简单。
但是如果转化 "123ss"等字符串里包含非数值的字符串时,则会自动转化为 123,不会抛出异常。
想要验证 字符串是否是数值格式  可使用
strtol (__const char *__restrict __nptr, char **__restrict __endptr, int __base)
 nptr指向的字符串, 
strtol()函数检测到第一个非法字符时,立即停止检测,其后的所有字符都会被当作非法字符处理。合法字符串会被转换为long int, 作为函数的返回值。非法字符串,即从第一个非法字符的地址,被赋给*endptr**endptr是个双重指针,即指针的指针。strtol()函数就是通过它改变*endptr的值,即把第一个非法字符的地址传给endptr

    char *str1="1231",*endptr1;
    
char *str2="123sss",*endptr2;

    printf(
"atoi str2 is %i\n",atoi(str1));
    
int i,j;//atoi(str);
    i=strtol(str1,&endptr1,10);
    
if(*endptr1!=NULL){
        printf(
"endptr1 is %s\n",endptr1);
    }
    printf(
"str1 auto int %i\n",i);
    j
=strtol(str2,&endptr2,10);
    
if(*endptr2!=NULL){
        printf(
"endptr2 is %s\n",endptr2);
    }
    printf(
"str2 auto long int %i\n",j);


只有注册用户登录后才能发表评论。


网站导航: