简体   繁体   English

将int转换为char C

[英]Turn int to char C

I am trying to turn int like 72, 101, 108 to '72', '101', '108' . 我试图将int像72, 101, 108变成'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. 原始程序是,例如,我读取字符串"Hello\\n" ,然后获取每个字符的ASCII值,然后将这些int放入char数组中。

I tried: 我试过了:

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

But this will convert the int from ASCII back to the character. 但这会将int从ASCII转换回字符。

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? 从什么时候开始,这些'72', '101', '108'变成了字符? Char values are stored in 1 byte. 字符值存储在1个字节中。

You can use sprintf or snprintf . 您可以使用sprintfsnprintf To convert the integers to char arrays. 将整数转换为char数组。

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

Or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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