自己实现的atoi函数

来源:互联网 发布:淘宝 宝贝 排名 编辑:程序博客网 时间:2024/06/08 04:41

不多说,直接上代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int _atoi(const char *str, int len)
{
if(NULL == str)
{
perror("input string is NULL");
return 0;
}
int value = 0;
int sign = 1;
const char *ptr = str;
const char *end = str + len;
//跳过开头的空白符
while((ptr < end) && isspace(*ptr))
{
++ptr;
}
if( ptr == end )
{
perror("all character is space");
return 0;
}
//符号位判断,只要带"-"就是负数,带"+",不带符号或其他的都认为是1
sign = ('-' == *ptr) ? -1 : 1;
//带符号位的需要跳过符号位
if('-' == *ptr || '+' == *ptr)
{
++ptr;
}
while(ptr < end)
{
if(*ptr < '0' || *ptr > '9')
{
break;
}
value = value * 10 + *ptr - '0';
++ptr;
}
if(-1 == sign)
{
value = -value;
}
return value;
}


int main( int argc, char *argv[] )
{
if(argc > 1){
printf("%d\n",_atoi(argv[1], strlen(argv[1])));
}
return 0;
}

0 0
原创粉丝点击