Converting an integer to a string

Started by
4 comments, last by _Josh 23 years, 9 months ago
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...
Advertisement
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?
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
"Your superior intellect is no match for our puny weapons!"
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?
--------------------------Programmers don't byte, they nibble a bit. Unknown Person-------------------------
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
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.

This topic is closed to new replies.

Advertisement