itoa函数的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/moses1213/article/details/52400176
#include <iostream>
using namespace std;

//itoa函数的实现
void MyItoa(int x, char* str)
{
	int i, j;
	i = j = 0;
	char tmp[50];
	bool negative = false;
	if(x < 0)
	{
		x = -x;
		negative = true;
	}
		
	while(x > 0)
	{
		tmp[i++] = x%10 + '0';
		x /= 10;
	}
	
	if(negative)
		tmp[i++] = '-';
	tmp[i] = '\0';
	
	--i;
	while(i >= 0)
	{
		str[j++] = tmp[i--];
	}
	str[j] = '\0';
}
	
	

int main() {
	// your code goes here
	char str[50];
	MyItoa(-12345, str);
	cout << str << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/moses1213/article/details/52400176