m_atoi

自己实现atoi函数

函数定义:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('')才结束转化,并将结果返回(返回转换后的整型数)。

/*atoi:将字符型的数转换为整形的数*/
#include<stdio.h>

int my_atoi(char *str)
{
	int total = 0;
	int flag = 1;	//Determine positive and negative
	
	while(*str == ' ')
	{
		str++;
	}
	
	if(*str == '+')
	{
		str++;
	}else if(*str == '-')
	{
		flag = -1;
		str++;
	}

	while((*str >= '0')&&(*str <= '9'))
	{
		total = total * 10 + (*str - '0');
		str++ ;
	}
	return total*flag;
}

	int main()
	{
		char *p ="   -12.8883abc";

		printf("%d
",my_atoi(p));
		return 0;
	}
原文地址:https://www.cnblogs.com/fanhua666/p/11446985.html