软讯网络 > 编程语言 > C/C++ > atoi函数
【标 题】:atoi函数
【关键字】:
atoi
【来 源】:http://blog.chinaunix.net/article.php?articleId=53938&blogId=8556
atoi函数

又被人问了这个,自己简单写了一个,然后看了别人写的,发现自己还真是头脑简单,再这样下去怎么活啊;
这是俺的简易版本,5分钟左右;
int atoi(char * str){ int length, value , base ; int idx; if(!str) return 0; length = strlen(str); if(length <= 0) return 0; base = 1; value = 0; for(idx = length-1; idx>0 ; idx--){ value+= (str[idx] - '0') * base; base *= 10; } if(str[idx] == '-'){ value = -value; }else{ value += (str[idx] - '0') *base; } return value; } |
这个是solaris里面的
#define ATOI #ifdef ATOI typedef int TYPE; #define NAME atoi #else typedef long TYPE; #define NAME atol #endif TYPE NAME(const char *p) { TYPE n; int c, neg = 0; unsigned char *up = (unsigned char *)p; if (!isdigit(c = *up)) { while (isspace(c)) c = *++up; switch (c) { case '-': neg++; /* FALLTHROUGH */ case '+': c = *++up; } if (!isdigit(c)) return (0); } for (n = '0' - c; isdigit(c = *++up); ) { n *= 10; /* two steps to avoid unnecessary overflow */ n += '0' - c; /* accum neg to avoid surprises at MAX */ } return (neg ? n : -n); } |
考虑得可真细致!!
【相关评论】
比尔那么有钱,“再这样下去怎么活啊!”