把整数的各位数字加‘0’转换成char类型,并存到字符数组中,程序如下,可在Visual studi0 2010 下运行
#include<iostream>
using namespace std;
void int2str(int n, char * str)
{
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n : n;
if(str == NULL)
{
return;
}
while(temp)
{
buf[i++] =(temp % 10) + '0'; // 把temp中的每一位数字加上‘0’变成字符逆序存在buf中
temp = temp / 10;
}
len = n < 0 ? ++i : i;
str[i] = 0; //末尾是结束符‘\0’;
while(1)
{
i--;
if(buf[len -i - 1] == 0)
{
break;
}
str[i] = buf[len - i -1];
}
if(i == 0)
{
str[i] = '-';
}
}
int main()
{
int nNum;
char p[10];
cout <<"please input an integer:";
cin >> nNum;
cout << "output: ";
int2str(nNum,p);
cout << p <<endl;
return 0;
}