int to char

I'm having trouble getting an int to cast to char in a way that the char will display the actual value of the int.
Say I have an int with a value of 5001, and I have a function that only takes char array[] variables. How do I get the actual value of 5001 into a char string?

The function only takes char strings, so using string is out.

Is there a function that already does this or would I have to make one from scratch?
The only solution I could think of on short notice was to output the number to a file then read from that file into a char[]. Now I can toss out that function, Thank you to TheGrayWolf.
The function only takes char strings, so using string is out

That needn't be a problem. Get a cstring from a c++ std::string using the .c_str() function.
http://www.cplusplus.com/reference/string/string/c_str/

You'd probably use a stringstream to get the value into the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void somefunction(const char * p)
{
    cout << "p = " << p << endl;
}

int main()
{
    int num =  5001;

    ostringstream os;
    os << num;
    somefunction( os.str().c_str() );


    char array[100];
    itoa(num, array, 10);
    somefunction(array);

    return 0;
}

Well, maybe itoa() is simpler
Last edited on
Topic archived. No new replies allowed.