/*题目2:(简答题:10.0分)
编程实现将整型数值转换为字符串。
char *my_itoa(int value, char *buffer, int radix);
参数说明:
value:欲转换的数值。
buffer:目标字符串的地址。
radix:转换后的进制数,可以是2进制,10进制、16进制等。
示例: value = 10; radix = 2; string=“1010”
不考虑value 为负数。
与函数
int sprintf(char *string, char *format ,…);
比较,有什么不同;
#include <iostream>
#include <ctype.h>
#include <limits.h>
#include <stack>
using namespace std;
char my_itoa_single(int p,int radix)
{
if(radix == 16 && p >= 10)
{
return p + 'W';
}
else
{
return p + '0';
}
}
void my_itoa(int value, char *buffer, int radix)
{
char * p = buffer;
int itmp = 0;
char ctmp;
stack<char> sta;
if(radix != 10)
{
*p = '0';
++p;
if(radix == 16)
{
*p = 'X';
++p;
}
}
while(value)
{
itmp = value%radix;
value = value/radix;
ctmp = my_itoa_single(itmp,radix);
sta.push(ctmp);
}
while(!sta.empty())
{
*p = sta.top();
sta.pop();
++p;
}
}
int main()
{
char buffer[100] = {0};
my_itoa(10, buffer,2);
printf("%s\n",buffer);
}
/*
sprintf将一个格式化的字符串输出到目标字符串中,可以,以多种格式输入到目标字符串,10,2,16,8等进制
,还可以弄浮点数,将两个字符串连接起来,常见的错误,目标字符串不够大而产生的溢出问题。
*/