C语言模拟实现atoi函数

来源:互联网 发布:mac怎么卸载驱动 编辑:程序博客网 时间:2024/05/17 03:08
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <assert.h>enum{INVALUE,VALUE};int my_atoi(char *str){int tmp = 0;int flag = 1;int num = 0;//空指针assert(str != NULL);    //空字符串if (*str == '\0'){return 0;}//空格处理while (isspace(*str)){str++;}//+  -if (*str == '-'){str++;flag = -1;}//异常字符处理while (isdigit(*str)){    tmp = tmp * 10 + (*str -'0')*flag;str++;//溢出处理if ((tmp > INT_MAX) || (tmp < INT_MIN)){num = INVALUE;}else{num = VALUE;}}return tmp;}int main(){int a = my_atoi("");int b = my_atoi("   ");int c = my_atoi("1234");int d = my_atoi("-1234");int e = my_atoi("   1234");int f = my_atoi("iii1234");int g = my_atoi("122344443433232323234");int h = my_atoi("-12333333333333333333");printf("%d\n", a);printf("%d\n", b);printf("%d\n", c);printf("%d\n", d);printf("%d\n", e);printf("%d\n", f);printf("%d\n", g);printf("%d\n", h);system("pause:");return 0;}

输出结果:



原创粉丝点击