C++字符串和整数相互转换

//将整数转化为字符串,并且不使用itoa函数
#include
void main()
{
	int n = 12345;
	char temp[6] = {0};
	int i = 0;
	while (n)
	{
		temp[i++] = n % 10 + '0';//整数加上‘0’隐性转化为char类型数
		n /= 10;
	}
	char dst[6] = {0};
	for (int j = 0; j < i; j++)
	{
		dst[j] = temp[i-1-j];
	}
	printf("%s\n", dst);
}

//将字符串转化为整数
#include
void main()
{
	char temp[6] = {'1','2','3','4','5'};
	int n = 0, i = 0;
	while (temp[i])
	{
		n = n * 10 + (temp[i++] - '0');//隐性转化为整数
	}
	printf("%d\n", n);
}


你可能感兴趣的:(SimpleCode)