简体   繁体   中英

Converting an int to a char in C?

I'm trying to add an int to a char array. 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. 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:

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.

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.

You'll want to use 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.

use 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

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