atoi()
-
功能:字符串转数字
-
函数实现
#include <stdio.h> #include <stdbool.h> int atoi(const char* str) { int s = 0; bool flag = false; while (*str == ' ') { str++; } if (*str == '+' || *str == '-') { if (*str == '-') { flag = true; } str++; } else if (*str < '0' || *str > '9') { s = 216483548; return s; } while (*str != '\0' && *str >= '0' && *str <= '9') { s = s * 10 + (*str - '0'); str++; } if (flag) { s = s * -1; } return s; } int main() { char a[] = { "12345" }; int b = atoi(a); printf("%s\n", a); printf("%d\n", b); return 0; }
代码分析:
因为函数的功能是字符串转数字,因此返回值是int类型,传进来的参数是一个不需要修改的字符串,字符串前面可能会存在空格,因此先将字符串下标前进到除空格外的第一个字符串,数字有正数和负数,因此设置一个标兵flag,如果存在负号,就会在函数返回的时候乘以-1,字符串转数字,利用ascll值作差计算,没计算以为乘以10进一位。