Archived

This topic is now archived and is closed to further replies.

_Josh

Converting an integer to a string

Recommended Posts

_Josh    122
I''m trying to create a function that would take an integer parameter and return a char* to the string. I found a function that will do the opposite ( strtoul ), so I''m assuming it is out there somewhere...

Share this post


Link to post
Share on other sites
_Josh    122
Nevermind, I found:

char* _itoa(int, char*, int)

I have a new question, though. The first parameter is the number to be converted, the second is the destination of the string, and the third is the base. What does it return? The string result? If the function already takes the string destination as a parameter, why would it return it too?

Share this post


Link to post
Share on other sites
Ironblayde    130
Beats me, but you could also use sprintf for this conversion. It works just like printf except writes data into a string instead of sending it to the screen. Something like this:

char buffer[4];
int x = 566;
sprintf(buffer, "%d", x);

Since you can use all those format specifiers like %d, this is a pretty versatile function, but if you're using this for something that's speed-critical, I'm not sure how fast sprintf() is...

-Ironblayde
 Aeon Software

Edited by - Ironblayde on July 22, 2000 2:18:10 AM

Share this post


Link to post
Share on other sites
Arjan    122
quote:
Original post by _Josh

Nevermind, I found:

char* _itoa(int, char*, int)

I have a new question, though. The first parameter is the number to be converted, the second is the destination of the string, and the third is the base. What does it return? The string result? If the function already takes the string destination as a parameter, why would it return it too?


Maybe it returns NULL when the integer doesn''t fit the string?

Share this post


Link to post
Share on other sites
Serge K    154
quote:
Original post by Arjan

Maybe it returns NULL when the integer doesn''t fit the string?



No, it doesn''t - It is impossible to get ammout of allocated memory from arbitrary pointer.

And check this: _itoa

Share this post


Link to post
Share on other sites
foofightr    130
quote:
Original post by _Josh

I have a new question, though. The first parameter is the number to be converted, the second is the destination of the string, and the third is the base. What does it return? The string result? If the function already takes the string destination as a parameter, why would it return it too?


It is useful to return the string, if you plan to use it *right away*, like here:

printf("%d is %s", myint, itoa(myint, mystr, 10));

In that case, it returns ''mystr'' so that it can be used in the printf function.

I guess it''s a more constructive use of the return value to indicate success or failure, rather than use 0 or 1.

Share this post


Link to post
Share on other sites