#include#include #include int my_atoi(char *str){ if(NULL == str) { printf("argc is null\n"); return -1; } while(' ' == *str) str++; int flag = 1; if('-' == *str) { flag = -1; str++; } if('+' == *str) { str++; } unsigned int sum = 0; while(*str) { if(*str >= '0' && *str <= '9') { int tmp = *str - '0'; sum *= 10; sum += tmp; //此处判断溢出的目的是避免sum在计算过程中溢出 if((1 == flag) && (sum > INT_MAX)) { printf("int 正数溢出\n"); return -1; } //计算最小int的绝对值,注意要使用unsigned int否则会溢出 unsigned int absIntMin = (unsigned int)INT_MAX + 1; if((-1 == flag) && (sum > absIntMin)) { printf("int 负数溢出\n"); return -1; } } else { printf("str (%s) exists illegal character\n", str); return -1; } str++; } return flag * sum;}
测试代码
#include#include extern int my_atoi(char *str);int main(int argc, char *argv[]){ char a[20] = { '\0'}; while(1) { scanf("%s", a); printf("count = %d\n", my_atoi(a)); } return 0;}