C库中的itoa()函数的实现

最近要准备校招了,看到好多题目是写一个小算法,比如自己写一个itoa()int转char的函数。

本人愚见,没有经过严格的测试,全当是做题,练习,毕竟轮子已经有了。

环境是win10 + vs2017 代码仅供参考,基本没有任何价值。

上代码:

#include <iostream>
#include <math.h>
#include <stdio.h>

void int2str(int num,char*& str)
{
	int n_num = 0;
	int nnum = num;
	int temp = 0;
	while (nnum)
	{
		nnum /= 10;
		n_num++;
	}
	str = (char*)malloc(sizeof(char)*n_num);
	for (int i = 0; i < n_num; ++i)
	{
		temp = num % 10;
		num /= 10;
		str[n_num - 1 - i] = temp + 48;		
	}	
}
int main()
{	
	int A = 12340;
	char* str;
	int2str(A,str);
	for (int i = 0; i < 5; ++i)
	{
		printf("%c",str[i]);
	}
	return 0;
}

 


版权声明:本文为m0_38036750原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。