Converting an int into a char[]?

Aug 6, 2009 at 3:45am
I'm using a function that outputs text on the screen, but only accepts a const char*. So I made a function that would take each digit and put it into a char[](called a C style string i think?).

Unfortunately when I did this all it would output seemed to be garbage data(although alot of the characters were the same, so it could be something else)
Could someone help me convert some ints into char[]s?

Here's the function i made:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char* intToChar(int x)
{
     char* y = NULL;
           y = new char[255];
     int count = 0;
     
     while(x!=0)
     {
     y[count] = (char)(x%10);
     x /= 10;
     count++;
                
                }
                return y;
     
     }
Aug 6, 2009 at 4:35am
There is a function already built-in that you can use: itoa().

BUT, since you are learning C++, you might want to understand what is going on with yours.

Assuming your math is correct (I did not pay attention to it), your problem lies on line 9. Instead, you need:
 
y[count] = (char)(x % 10 + '0');


A value of zero casted as a char will yeild a character whose code is zero, and that character is NOT the character that represents the number zero.
Aug 6, 2009 at 6:27am
There is a function already built-in that you can use: itoa().
No, there isn't.

You can find exactly how many characters you'll need by dividing the number by ten until it becomes zero.
Aug 6, 2009 at 12:42pm
helios, I'm confused. I have used itoa() in the past to get string representations of numbers.

What do you mean?
Aug 6, 2009 at 1:12pm
Aug 6, 2009 at 1:14pm
Read: http://www.cplusplus.com/forum/articles/9645/ to find out one of the better ways to do conversions.

Also, itoa() is non-standard.
Aug 6, 2009 at 2:04pm
Ok I tried what WebJose told me, and it still doesn't seem to work.. All it seems to output are '^' and 'x', and i'm not sure why. Since itoa doesn't seem like a good idea to use, i'm thinking about using stringstreams. But if i put a string where a char[] is supposed to be, would it still work?

edit: Tried the stringstream approach, but it wouldn't take the string. Is there a function to convert string to char[]?
Last edited on Aug 6, 2009 at 2:19pm
Aug 6, 2009 at 2:25pm
use string::c_str() to get a const char*, then use strncpy to copy it to a modifiable char array http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
Last edited on Aug 6, 2009 at 2:26pm
Aug 6, 2009 at 2:48pm
Ah thanks, but i found the function sprintf(), and it worked fine.
Topic archived. No new replies allowed.