views:

140

answers:

3

Hi, I was looking for a way to convert an integer to a string in a portable manner (portable among at least Windows & Linux and x86 and x86_64) and I though itoa(X) to be standard just like atoi(1).

But I read the following in the Wikipedia entry:

The itoa function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header while in non-conforming mode, because it is a logical counterpart to the standard library function atoi.

So I'd like to know if there is any way to do it in a portable manner or not. In case I have to write my own function, which things do I have to be careful with?

+6  A: 

sprintf(), or snprintf() in C99.

Ignacio Vazquez-Abrams
snprintf() is better.
Robert Gamble
However the printf family of functions are quite slow, so if you're using this heavily, itoa is a better option, and as said, it's not that hard to write (there's even an implementation on the wiki page).
Will Hartung
or _snprintf in Windows.
R Samuel Klatchko
Yes, I saw the implementation but the same page warned itoa(X) was not portable, maybe the person who wrote that was talking about the interface; depending on the implementation it may have different arguments. By the way, thank you for the suggestion Ignacio!
Dimitri Spirtovic
+1  A: 

Most often you just use printf("%d");

http://en.wikipedia.org/wiki/Printf

You can use sprintf if you need it in a buffer, but how often do you convert to a string and not write it to a file or output device?

Hogan
A: 

If you aren't doing this terribly often, how about a runtime library routine that writes a few numbers to memory, analyzes the results and stores an encoding type? From then on you just switch on your "encoding type" to select which conversion routine to use.

Bill K