现在的位置: 首页 > 综合 > 正文

my itoa 简单实现

2013年11月06日 ⁄ 综合 ⁄ 共 643字 ⁄ 字号 评论关闭
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * (正负)整数转字符串
 * */
void my_itoa(int n,char* out_put)
{
	/*
	 *先取绝对值
	 * */
	int tmp = n < 0 ? -n : n;

	char buf[1024] = {0};
	int i = 0;
	while(tmp)
	{
		/*
		 * 加'0'是把数字转换成字符
		 * */
		buf[i++] = (tmp % 10) + '0';
		/*
		 * 逐个取整数的每一位
		 * */
		tmp = tmp / 10;
	}
	/*
	 * 末位加字符串结束标志
	 * */
	buf[i] = '\0';

	/*
	 *负数的话多留一位来填 '-' 负号
	 * */
	int len = n < 0 ? ++i : i;

	int j;
	/*
	 * 因为buf中的顺序是倒的,所以把buf中的填到out_put中去
	 * 注意:整数和负数的区别,负数多一个符号位,所以多减去1
	 * */
	for(j = 1; j <= len; j++)
		out_put[j] = n < 0 ? buf[len - j - 1] : buf[len - j];	

	/*
	 * 最后填符号位
	 * */
	out_put[0] = n < 0 ? '-' : '+';

	/*
	 * 末位加字符串结束标志
	 * */
	out_put[j] = '\0';
}

int main()
{
	int n;
	printf("Enter a integer:\n");
	scanf("%d",&n);
	char* tmp = (char*)malloc(1024);
	memset(tmp,0,1024);
	my_itoa(n,tmp);
	printf("%s\n",tmp);
	return 0;
}

 

抱歉!评论已关闭.