0

How do you put an int into a char array?

int x = 21, i = 3;
char length[4];

while(i >= 0) {
    length[i] = (char) (x % 10);
    x /= 10;
    i--;
} printf("%s\n", length);

// length should now be "0021"

The string comes out blank instead.

Note: This is not a duplicate of "How do I convert from int to chars in C++?" because I also need padding. i.e. "0021" not "21"

12
  • what are you trying to do? -> snprintf(length, sizeof(length), "%d", x);? Commented Mar 27, 2015 at 12:37
  • possible duplicate of How do I convert from int to chars in C++? Commented Mar 27, 2015 at 12:39
  • @MuertoExcobito where is c++? Commented Mar 27, 2015 at 12:40
  • 1
    sprintf(length, "%04d", x); Of course, you'll want to increase the size of length, for the null terminator. Commented Mar 27, 2015 at 12:53
  • 1
    @RussellHickey you can add padding like this snprintf(length, sizeof(length), "%0*d", numberOfDigits, value); Commented Mar 27, 2015 at 12:53

2 Answers 2

6

You're not getting the character code of the digit, you're using the digit as if it were its own character code. It should be:

length[i] = '0' + (x % 10);

You also need to add an extra element to the length array for the terminating null character:

char length[5];
length[4] = 0;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You, it worked. I'll accept the answer when allowed. :)
Shouldn't it be length[4] = '\0';?
They're the same thing.
2

The problem in your code is basically that 1 != '1' i.e. the character is not the integer, you need to check the ascii table to see what ascii code represents the character '1' but you don't really need to know the number, you can just use '1' note the single qoutes.

But you also didn't nul terminate your string, you need to add a '\0' at the end of the string, so

int x = 21, i = 3;
char length[5];

length[4] = '\0';
while (i >= 0) 
{
    length[i--] = x % 10 + '0';
    x          /= 10;
} 
printf("%s\n", length);

should work, but is unecessary, you can just

snprintf(length, sizeof(length), "%0*d", padding, x);
/*                                         ^ this is how many characters you want */

notice that sizeof works because length is a char array, do not confuse that with the length of a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.