views:

123

answers:

7

Possible Duplicate:
C++ convert int and string to char*

Hello, i am making a game and I have a score board in it. The score is stored in an int variable but the library im using for the game needs an array of chars for its text outputting for my scoreboard.

So how do i turn an int into an array of chars?

int score = 1234;  // this stores the current score

dbText( 100,100, need_the_score_here_but_has_to_be_a_char_array); 
// this function takes in X, Y cords and the text to output via a char array

The library im using is DarkGDK.

tyvm :)

A: 
char str[10];  
sprintf(str,"%d",value);
Shaihi
don't forget your semi colon :D
KennyCason
`value = -1000000000` and... poof! Your code doesn't work anymore.
ybungalobill
@ybungalobill: I do expect people using an answer to think and understand what they do - this is why the code is an example... Funny thing is there is one more answer with the exact same problem for which no down vote has been given.
Shaihi
+7  A: 
ostringstream sout;
sout << score;
dbText(100,100, sout.str().c_str());
ybungalobill
This would be my suggestion too. Just keep in mind that .str() returns a temporary object, so caching the result of .str().c_str() is a BAD IDEA. (This doesn't apply in your example, but I wanted to be sure that caveat was mentioned).
Tim
+2  A: 

You can use an std::ostringstream to convert the int to an std::string, then use std::string::c_str() to pass the string as a char array to your function.

Charles Salvia
+1  A: 
char str[16];
sprintf(str,"%d",score);
dbText( 100, 100, str );
Rod
A: 

Well, if you want to avoid C standard library functions (snprintf, etc.), you could create a std::string in the usual manner (std::stringstream, etc.) and then use string::c_str() to get a char * which you can pass to the library call.

Oli Charlesworth
+3  A: 

Use sprintf

#include <stdio.h>

int main () {
  int score = 1234; // this stores the current score
  char buffer [50];
  sprintf (buffer, "%d", score);
  dbText( 100,100,buffer);

}
Preet Sangha
A: 

Let me know if this helps.

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {
    char ch[10];
    int i = 1234;
    itoa(i, ch, 10);
    cout << ch[0]<<ch[1]<<ch[2]<<ch[3] << endl; // access one char at a time
    cout << ch << endl; // print the whole thing
}
KennyCason