Sign in to follow this  
kelcharge

Converting int to const char*?

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
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
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this