【C语言】编写函数实现库函数atoi,把字符串转换成整形

时间:2021-06-07 21:52:35
//编写函数实现库函数atoi。把字符串转换成整形
#include <stdio.h>
#include <string.h>
int my_atoi(const char *src)
{
int flag=1;
int sum=0;
while (*src)
{
if (*src == ' ')
src++;
else if (*src == '+')
{
src++;
flag = 1;
}
else if(*src == '-')
{
src++;
flag = -1;
}
else if(*src >= '0'&&*src <= '9')
{
sum = sum * 10 + (*src - '0');
src++;
}
else
{
return 0;
}
}
sum = sum*flag;
return sum;
}
int main()
{
printf("%d\n", my_atoi(" +12345"));
printf("%d\n", my_atoi(" -12345"));
printf("%d\n", my_atoi("+12345"));
printf("%d\n", my_atoi("-12345"));
printf("%d\n", my_atoi("123 45"));
printf("%d\n", my_atoi("234 5"));
printf("%d\n", my_atoi(""));
printf("%d\n", my_atoi("123ab"));
return 0;
}