// 模拟实现库函数的atoi函数
程序:
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>//isspace判断字符是否为空白字符
int my_atoi(char const *p)
{
int ret = 0;
int a = 0;
int flag = 1;
assert(p != NULL);
while (isspace(*p))
{
p++;
}
while (*p)
{
if (*p == '+')
p++;
else if (*p == '-')
{
p++;
flag = -1;
}
else if (*p >= '0'&& *p <= '9')
{
a = *p - '0';
ret = (ret * 10 + a);
p++;
}
else
return 0;
}
if ((flag == 1 && ret > 0x7FFFFFFF) || (flag == -1 && ret < (signed int)0x80000000))
return 0;
return ret*flag;
}
int main()
{
printf("%d\n", my_atoi(" +2345"));
printf("%d\n", my_atoi(" -2345"));
printf("%d\n", my_atoi("+2345"));
printf("%d\n", my_atoi("-2345"));
printf("%d\n", my_atoi("2345"));
printf("%d\n", my_atoi(""));
printf("%d\n", my_atoi("xiaoxiao"));
return 0;
}
结果:
2345
-2345
2345
-2345
2345
0
0
请按任意键继续. . .