简体   繁体   中英

Turn int to char C

I am trying to turn int like 72, 101, 108 to '72', '101', '108' .

The original program is that I am read the string "Hello\\n" for example, then get the ASCII values of each character, then put those int into a char array.

I tried:

int a = 72;
char b = (char)a; 

But this will convert the int from ASCII back to the character.

I also tried:

int a = 72;
char b = a + '0';

But this just does not work at all.

This is what I have:

char buff[128];
strcpy(buff, "Hello\n");

char tmp[128];
bzero(tmp, 128); // initialize array

int n = 0;
while(buff[n] != '\n') {
   int ascii = (int)buff[n];
   en[n] = (char)ascii; // RIGHT HERE
   n++;
}
strcat(tmp, "\n");

fprintf(stdout,"%s", tmp);

Since when did these '72', '101', '108' become chars? Char values are stored in 1 byte.

You can use sprintf or snprintf . To convert the integers to char arrays.

int c = 4;
char tin [Some_Length];
sprintf(tin , "%d", c);

Or

snprintf(tin , Some_Length, "%d", c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM