源码实现 --> atoi函数实现

atoi函数实现

  atoi()函数的功能是将一个字符串转换为一个整型数值。

 

例如“12345”,转换之后的数值为12345,“-0123”转换之后为-123。

#include <stdio.h>
int my_atoi(const char *str) { int total = 0; //保存转换后的数值 int isNegative = 0; //记录字符串中是否有负号 int length = 0; //记录字符串的长度 const char *p = str; char temp = '0'; if(NULL == p) //判断指针的合法性 { printf("error"); return -1; } while(*p++!='\0') //计算字符串的长度 { length++; } p = str; //重新指向字符串的首地址 if(*p == '-') //判断是否有负号 { isNegative = 1; } for(int i = 0;i < length;i++) { temp = *p++; if(temp > '9'||temp < '0') //滤除非数字字符 { continue; } if(total != 0||temp != '0') //滤除字符串开始的0字符 { temp -= '0'; total = total*10 + temp; } } if(isNegative) //如果字符串中有负号,将数值取反 return (0 - total); else return total; //返回转换后的数值 } int main(int argv,char *argc[]) { printf("%d\n",my_atoi("-0123")); return 0; }

执行结果:-123

posted @ 2016-03-29 14:27  蚂蚁吃大象、  阅读(2550)  评论(0编辑  收藏  举报