将整数值存储在C中的字符数组中 [英] Store an integer value in a character array in C
问题描述
这是一个非常小的问题,但我不知道为什么我没有得到正确的输出。这是我想要做的:
It is a very trivial question but I don't know why I am not getting the correct output. Here is what I am trying to do:
char sendBuffer[1000];
int count=0:
while(count<10)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
在输出中,除第一个索引外,所有缓冲区都正确打印。我想要1,2,3等等打印在缓冲区的开始,但它不工作。请帮助
In the output, all buffer is printed correctly except the first index. I want 1,2,3 and so on to be printed at the start of the buffer but it does not work. Please Help
推荐答案
您需要将该数字转换为字符。一个便宜的方法是:
You need to convert that number into a character. A cheap way to do it is:
sendBuffer[0] = '0' + count;
无论如何显示大于9的整数
is there anyway to display integers greater than 9
如果你需要,你会想转移到更复杂的方案。例如,如果要将整数42转换为字符串42,您可以说:
If you need that you'll want to shift to more elaborate schemes. For example, if you want to convert an integer 42 into the string "42" you can say:
#define ENOUGH ((CHAR_BIT * sizeof(int) - 1) / 3 + 2)
char str[ENOUGH];
snprint(str, sizeof str, "%d", 42);
贷款 ENOUGH
转到 caf 。
这篇关于将整数值存储在C中的字符数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!