天天看點

c函數itoa和atoi實作

#include <stdio.h>

int atoi( char *string)
{
	int sum = 0;
	int sign = 1;
	for (int i = 0; string[i] != '\0'; i++)
	{
		if (string[i] >= '0' && string[i] <= '9') //去掉一些特殊符号
		{
			sum = sum * 10 + (string[i] - '0');
		}
		if (i == 0 && string[i] == '-') //判斷開頭是不是負值
		{
			sign = -1;
		}
	}

	return sign*sum;
}

void itoa(int n, char *str)
{
	char *t = str; //緩存頭指針 便于後面列印
	int temp = n;
	if (n < 0) //先判斷正負
	{
		*str++ = '-';
		temp = -temp;
		n = -n;
	}
	
	int te = 1;
	for (; temp > 10; temp /= 10)
	{
		te *= 10;
	}

	for (; te >= 1; te /= 10)
	{
		
		*str++ = '0' + n / te;
		n = n % te;
	}

	*str = '\0';
	printf("%s\n", t);
}

int main()
{
	char string[20] = "-123&%45";
	printf("%d\n", atoi(string));

	char str[20];
	itoa(-123,str);
	cout << str << endl;

	system("pause");
	return 0;
}