在C里面,如何将一个int型转换为char型,比如将123变为"123"

Tony007 2002-05-24 11:06:43
不是ASIIC的转换,要保持内容不变
...全文
329 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
rkwj 2002-05-24
  • 打赏
  • 举报
回复
int n;
(char) n;
huamulan 2002-05-24
  • 打赏
  • 举报
回复
itoa, sprintf 均可
coyj 2002-05-24
  • 打赏
  • 举报
回复
用库函数#include <stdlib.h>
char *itoa(int num,char *str,int radix);
或自己编写函数实现,下面是我的函数库实现,有问题请email:coyj@163.com
#ifdef PERDURE
#undef STATIC
#define STATIC static
#else
#undef STATIC
#define STATIC
#endif
/****************************************************
函数名:ltostr
功能:把长整形转换成以0结尾的字符串
参数列表:
num 被转换的数字
radix 转换后的进制数
dest 存储转换后的字符串,必须足够长
返回值:转换后的字符个数
说明:
radix不能大于36,
否则什么也不做并返回0
如果需要重复的调用,可定义PERDURE使基数表不必
多次的重复释放分配
****************************************************/
int ltostr(long num,char *dest,int radix)
{
int i=0,j=0;
char temp_char;
int temp_count;
STATIC const char *radix_table="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

if(radix>36||radix<2||dest==NULL) return 0;

while(num>=radix)
{
*(dest+i++)=*(radix_table+num%radix);
num/=radix;
}
*(dest+i)=*(radix_table+num);

temp_count=i+1;
*(dest+temp_count)='\0';

while(j<i)
{
temp_char=*(dest+j);
*(dest+j++)=*(dest+i);
*(dest+i--)=temp_char;
}

return temp_count;
}
fat_horse 2002-05-24
  • 打赏
  • 举报
回复
itoa不是标准C的函数,
最好不用。
用snprintf而不是sprintf,
这个好习惯。
wuhuar 2002-05-24
  • 打赏
  • 举报
回复
itoa()
HostOOP 2002-05-24
  • 打赏
  • 举报
回复
最偷懒的方法就是使用sprintf():

char cnum[8];
sprintf(cnum,"%ld",(long)number);

huanyun 2002-05-24
  • 打赏
  • 举报
回复
用wsprintf比较好
TempTask 2002-05-24
  • 打赏
  • 举报
回复
int i = 123456;

char Buf[20];

itoa(i,Buf,10);

for(int j = 0;j < strlen(Buf);j ++) Buf[j] -= '0';
fangrk 2002-05-24
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 12345;
char string[10];

itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}
fang_jb 2002-05-24
  • 打赏
  • 举报
回复
int a=123;
char b[20];
memset(b,0,sizeof(b));
sprintf(b,"%d",a);

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧