• Advertisement
Sign in to follow this  

Converting int to const char*?

This topic is 4574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to know how I could convert an int to a const char*. I am making a game engine and I want to put the Maps x and y positions on the screen while the game is running. The maps position is in an int but the textout function needs const char*. Any help would be very much appreciated.

Share this post


Link to post
Share on other sites
Advertisement
Assuming C++, you can either use boost::lexical_cast or a std::stringstream to get a string that you can access with c_str().

std::stringstream sstr;
sstr << my_int;
const char * ptr1 = sstr.str().c_str();

std::string str = boost::lexical_cast<std::string>(my_int);
const char * ptr2 = str.c_str();

Share this post


Link to post
Share on other sites
If you care about portable code I highly recommend avoiding itoa(). It is severly non-standard. Not only is it not part of the C standard library, but in non-standard implementations I've seen at least five different function signatures for itoa(), with different memory management conventions:

char * itoa(int, char *, int); // you supply the buffer
char * itoa(int, int, char *); // you supply the buffer
char * itoa(int, char *); // you supply the buffer
char * itoa(int, int); // you need to free the pointer
char * itoa(int); // you need to free the pointer

Share this post


Link to post
Share on other sites
Quote:
Original post by kelcharge
Would itoa() be a route to go?


Better to use strtod, strtol, strtoul. Not only do these calls support specifying the end of the string as a pointer but the strtol and strtoul support different base types so you can convert hex, octal, binary, etc.

Share this post


Link to post
Share on other sites
assign the int into a char, then cast that to a char *

int i = 124;
char c = i;
char *s = (char *)c;

sounds like you want to do some ASCII backgrounds? if so you only need 1 character per (x,y) coordinate right?

Share this post


Link to post
Share on other sites
Quote:
Original post by Interesting Dave
assign the int into a char, then cast that to a char *

int i = 124;
char c = i;
char *s = (char *)c;


Erm, whaaat?

Forgive me but I'm speechless.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
no, im pretty sure he jsut want to output corrdinants. what you were sugesting would not work, as char is still a number, so putting an int in it (like 124) would result in the char printing whatever character is 124 in ascii.

you could always make a function that separates an int into units (1's, 10's, 100's, etc) using division and such, then convert those numbers to characters by adding the appropriate ascii value (i cant remember what it is, i think its around 90) this would probably be easiest using recursion. of course, i highly doubt the method the best,or fastest way (actually, its probably in the area of worst, slowest, and most memory consuming)

Share this post


Link to post
Share on other sites
why not just print it to a string?!

int i = 9;
char* str = new char[2];
sprintf(str, "%i", i);

then pass to the function.

function((const char*)str);

Share this post


Link to post
Share on other sites
ahhh.. that makes more sense (I re-read the OP)..

I was thinking he wanted something like nethack - where everything is displayed as an ASCII character: since each x,y position can only be displayed as 1 character..

Share this post


Link to post
Share on other sites
Quote:
Original post by anonuser
int i = 9;
char* str = new char[2];
sprintf(str, "%i", i);

That's ok if the number is 0 - 9, but if the number is > 9 or < 0, you are in big trouble. You could use snprintf, but even that function has problems. sprintf should generally be avoided since there are other safer alternatives.

Share this post


Link to post
Share on other sites
okay even better. this little equation will calculate the lenght of a the digit.
this only works for integers, but you work around that with fixed point notation.
log(i)/log(10) + 1 + 1

the reason for plus one plus one is a null terminator.

or

pad the string, with the zeros to the maximum digits of the coord system -1, then print in


int i = 99;
char* text = new char[log(i) / log(10) + 2];

sprintf(text, "%d", i);

math is the ultimate problem solver.

Share this post


Link to post
Share on other sites
btw of this thread i also have a question: what to do if i wish to do it the other way round: i need to convert charaters (several digits) into int. i tried a couple of functions but they return some rubbish (most likely total of asci codes of the characters).

for now i got around this with the switch-case function but i think there must be some simpler way.

take care

peter

Share this post


Link to post
Share on other sites
As someone else said, you may want to stay away from itoa because of the differences on cross-platform. But if you're only going to be working with one compiler, then it shouldn't be a problem. You could easily make you're own though, a simple string convertor.

template<typename Tp>
Tp stringConvert(string szLine)
{
stringstream stream;
Tp ret;

stream << szLine;
stream >> ret;

return ret;
}

You would use this like so:
int i = stringConvert<int> ( str );

That should be right, I'm defragging a hard-drive right now and I just woke up (in the middle of the night even) so don't trust my judgement wholeheartedly. Test, test, and test some more. Good luck!

Share this post


Link to post
Share on other sites
While most of the already implemented solutions are better, I couldn't help but roll my own.

void intToStr(const int i, char*& szOut)
{
if(szOut)
delete [] szOut;

int nInAbs(abs(i));

int nPower10 = int(log10(nInAbs));

// number of characters + optional sign + null terminator
int nNumChars = nPower10+(i<0?1:0)+2;
szOut = new char[nNumChars];

char cPos=0;
if(i<0)
szOut[cPos++]='-';

int nTemp(nInAbs);
int nPower;
while(nPower10>=0)
{
nPower = int(pow(10,nPower10));
nTemp /= nPower;
szOut[cPos++]=nTemp+48;
nTemp = nInAbs%nPower;
nPower10--;
}
szOut[cPos]='\0';
}

//Usage:
char* sz;
sz=NULL;

intToStr(0,sz);
intToStr(1,sz);
intToStr(-123456789,sz);
intToStr(954238,sz);

delete [] sz;



Share this post


Link to post
Share on other sites
Since this little debug procedure was just temporary, I used itoa(). and it went like this.


const char* convert(int i, char* b) { //since char* and strings are the same thing
itoa(i, b);
return b;
}


Share this post


Link to post
Share on other sites
Are you using C or C++?

If you are using C++ you should strongly consider using std::string instead of char* as your string representation.

Then you can use boost::lexical_cast or your own stringstream implementation (and you can still get a const char* by using the std::string member function c_str()).

If you're using C then you'll have to use char* and you'll be responsible for allocating/freeing memory and at some point you will make a mistake.

Share this post


Link to post
Share on other sites
I am using C++, but this code isnt going to go into my game engine right now. I use it just for simple debug issues with bitmaps that I draw to the screen.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement