C语言 在C中将int转换为char?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21196926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting an int to a char in C?
提问by Rohan
I'm trying to add an int to a char array. My (broken) code is as follows,
我正在尝试将 int 添加到 char 数组中。我的(损坏的)代码如下,
string[i] = (char) number;
with ibeing some int index of the array and numberis some integer number. Actually, while typing this out I noticed another problem that would occur if the number is more than one digit, so if you have some answer to that problem as well that would be fantastic!
与i被所述阵列的一些INT索引和number是某一整数。实际上,在输入此内容时,我注意到如果数字多于一位,则会出现另一个问题,因此如果您对该问题也有一些答案,那就太棒了!
回答by Jonathan Leffler
Given the revised requirement to get digit '0'into string[i]if number == 0, and similarly for values of numberbetween 1and 9, then you need to add '0'to the number:
考虑到将 digit'0'转换为string[i]if的修订要求number == 0,并且对于numberbetween1和之间的值也类似9,那么您需要添加'0'到数字中:
assert(number >= 0 && number <= 9);
string[i] = number + '0';
The converse transform is used to convert a digit character back to the corresponding number:
逆变换用于将数字字符转换回相应的数字:
assert(isdigit(c));
int value = c - '0';
回答by Devolus
If you want to convert a single digit to a number character you can use
如果要将单个数字转换为数字字符,可以使用
string[i] = (char) (number+'0');
Of course you should check if the int value is between 0 and 9. If you have arbitrary numbers and you want to convert them to a string, you should use snprintf, but of course, then you can't squeeze it in a char aynmore, because each char represents a single digit.
当然你应该检查 int 值是否在 0 和 9 之间。如果你有任意数字并且你想将它们转换为字符串,你应该使用snprintf,但是当然,你不能把它挤在一个字符 aynmore 中,因为每个字符代表一个数字。
If you create the digit representation by doing it manually, you should not forget that a C string requires a \0byte at the end.
如果您通过手动创建数字表示,则不应忘记 C 字符串\0的末尾需要一个字节。
回答by Dan H
You'll want to use sprintf().
您将需要使用 sprintf()。
sprintf(string,'%d',number);
I believe.
我相信。
EDIT: to answer the second part of your question, you're casting an integer to a character, which only holds one digit, as it were. You'd want to put it in a char* or an array of chars.
编辑:要回答问题的第二部分,您将一个整数转换为一个字符,该字符只包含一个数字,就像它一样。你想把它放在一个 char* 或一个字符数组中。
回答by Anis_Stack
use asprintf :
使用 asprintf :
char *x;
int size = asprintf(&x, "%d", number);
free(x);
is better because you don't have to allocate memory. is done by asprintf
更好,因为您不必分配内存。由 asprintf 完成

