Rohan
Rohan

Reputation: 551

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!

Upvotes: 2

Views: 25770

Answers (4)

Anis_Stack
Anis_Stack

Reputation: 3452

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

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753930

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';

Upvotes: 5

Devolus
Devolus

Reputation: 22084

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.

Upvotes: 2

Dan H
Dan H

Reputation: 626

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.

Upvotes: 1

Related Questions