如何在C语言中将整数转换为字符?
如何在C语言中将整数转换为字符?
C语言中的char类型已经是一个数字(即字符的ASCII码),不需要进行转换。
如果你想将数字转换为对应的字符,可以直接加上'0':
c = i +'0';
'0'是ASCll表中的一个字符。
:
而不是我想要的 10
。ASCII表显示,整数10实际上是LF(换行符)。 - mLstudent33main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
这里提供另一个示例
#include <stdio.h>
int main(void)
{
char text[] = "StringX";
int digit;
for (digit = 0; digit < 10; ++digit)
{
text[6] = digit + '0';
puts(text);
}
return 0;
}
/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/
str[10]
而不是str[7]
呢?因为有6个数字,再加上1个用于'\0'
的结束符。 - IAbstractatoi
与此有何关系? - AnT stands with Russiaatoi
的作用与OP想要的相反。 - user376845int
赋值给一个 char
变量即可。int i = 65;
char c = i;
printf("%c", c); //prints A
将整数转换为字符时,只有0到9会被转换。我们知道0的ASCII值为48,因此我们必须将其值加到整数值上,以将其转换为所需的字符,因此
int i=5;
char c = i+'0';
将int转换为char,请使用以下方法:
int a=8;
char c=a+'0';
printf("%c",c); //prints 8
将char转换为int,请使用以下方法:
char c='5';
int a=c-'0';
printf("%d",a); //prints 5
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}