#include <stdio.h>
int my_atoi(char *str)
{
int flag = 1;
int ret = 0;
while (*str==' ') //跳过空格
{
str++;
}
if (*str == '\0')
{
return 0;
}
if (*str == '+') //接下来判断正负
{
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
while (*str)
{
if (*str == '-')
{
flag = -1;
str++;
}
if (*str >= '0'&&*str <= '9') //读取字符数字转换成整型
{
ret = ret * 10 + flag * (*str - '0');
str++;
}
else //不是数字就直接跳过
{
str++;
}
}
if(*str == '\0')
{
return printf("result :\t%d\n",ret);
}
}
int main ()
{
char str[100] = "0";
printf("please input a string :\n");
gets(str);
my_atoi(str);
return 0;
}
//运行结果

该博客展示了一段C语言代码,实现了自定义的atoi函数。代码中先跳过字符串前的空格,判断正负号,再将字符数字转换为整型,非数字字符则跳过,最后在主函数中获取用户输入的字符串并调用该函数输出结果。
667

被折叠的 条评论
为什么被折叠?



