Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an integer value in a character array in C

Tags:

c

char

int

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;
}

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

like image 343
Ayse Avatar asked Dec 11 '22 17:12

Ayse


1 Answers

You need to convert that number into a character. A cheap way to do it is:

sendBuffer[0] = '0' + count;

is there anyway to display integers greater than 9

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);

Credit for ENOUGH goes to caf.

like image 101
cnicutar Avatar answered Dec 28 '22 05:12

cnicutar