五一七教育网
您的当前位置:首页C语言实现atoi函数

C语言实现atoi函数

来源:五一七教育网
C语⾔实现atoi函数

作为itoa的兄弟,我也⼀并⾃⼰写了出来。

#include

int myatoi(const char* str);int main() {

char* str1 = \"-12\"; int a;

a = myatoi(str1); printf(\"%d\", a); return 0;}

int myatoi(const char* str) {

int value = 0; //存放值 int flat = 1; //判断正负 while(*str == ' ') { //跳过空字符 str++; }

if (*str == '-') { flat = 0; str++; }

else if (*str == '+') { flat = 1; str++; }

else if (*str<'0' || *str>'9') { //第⼀个字符为其他,直接跳出 return 0; }

while(*str >= '0' && *str <= '9' && *str != '\\0') { value = value * 10 + *str - '0'; str++; }

if (flat == 0) { value = -value; }

return value;}

因篇幅问题不能全部显示,请点此查看更多更全内容