相关知识:
头文件:#include <stdlib.h>
atoi() 函数用来将字符串转换成整数(int),其原型为:
int atoi (const char * str);
【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。
程序如下:
#include <stdio.h>
#include <stdlib.h>
int myatoi(const char *str)
{
int flag = 1;
int result = 0;
if(str == NULL)
return 0;
while(*str == ' ' || *str == '\t')
str++;
if(*str == '-')
{
flag = -1;
str++;
}
while(*str != '\0')
{
if(*str >= 0 && *str <= '9')
result = result*10 + (*str - '0');
else
{
break;
}
str++;
}
return result * flag;
}
int main()
{
char *s1 = "123jie";
char *s2 = "-323dkr";
printf("result = %d\n",myatoi(s1));
printf("result = %d\n",myatoi(s2));
return 0;
}
运行结果如图所示: