C++ converting an int to an array of chars? [duplicate]
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 :)
ostringstream sout;
sout << score;
dbText(100,100, sout.str().c_str());
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);
}
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.
char str[16];
sprintf(str,"%d",score);
dbText( 100, 100, str );
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.
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
}
char str[10];
sprintf(str,"%d",value);
精彩评论