[英]Converting an int to a char in C?
I'm trying to add an int to a char array. 我正在尝试将一个int添加到char数组中。 My (broken) code is as follows,
我的(破损)代码如下,
string[i] = (char) number;
with i
being some int index of the array and number
is some integer number. i
是数组的一个int索引, 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! 实际上,在输入时我注意到如果数字超过一位数就会出现另一个问题,所以如果你对这个问题有一些答案那就太棒了!
Given the revised requirement to get digit '0'
into string[i]
if number == 0
, and similarly for values of number
between 1
and 9
, then you need to add '0'
to the number: 如果
number == 0
,修改了将数字'0'
变为string[i]
,并且类似于1
到9
之间的number
值,则需要在数字中加上'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';
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
,但当然,你不能在char中使用它。 ,因为每个字符代表一个数字。
If you create the digit representation by doing it manually, you should not forget that a C string requires a \\0
byte at the end. 如果通过手动创建数字表示,则不应忘记C字符串最后需要
\\0
字节。
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 *或char数组中。
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完成的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.