atoi and iota seem like perfect partners.
atoi is the ‘ascii to integer’ function and itoa is the reverse, the ‘integer to ascii’ function.
You would use atoi to convert a string, say, “23557” to the actual integer 23557.
Similarly, you would use itoa to convert an integer, say 44711, to the equivalent string “44711”.
Very handy.
Now, if you’ve written a lot of code using Microsoft Visual C++ (which is where I first started when I was learning C and C++), you may not be aware of the fact that atoi is part of the ANSI standard, whereas itoa is not. The MSVC compiler supports itoa, so if you are coding on this platform – particularly if you are learning on this platform – then it appears that atoi and itoa are a complementary pair that would be available everywhere. Not so!
What does this mean?
It means that outside of the world of Microsoft Visual C++, most compilers don’t support the itoa function (including gcc).
I discovered this myself the very first time I was tasked with porting Windows code to Linux. At first I was completely floored by this – why on earth wasn’t itoa available? I was porting code that used atoi and itoa with alarming regularity. But more importantly, what was I going to use instead??
The answer to the first question is partly down to complexity. It is much harder to write an itoa function than it is to write an atoi function (try it!). But it is also down to the fact that that for the majority of cases there is already a function that you can use instead of itoa, so why reinvent the wheel.
And that supplies the answer to the second question – instead of itoa, you can use sprintf.
Admittedly, sprintf isn’t as neat and concise as itoa, and it can only deal with numbers in base 8, 10 and 16. However, for the most part, sprintf will do the job you require.
Here’s a code example:
#include <iostream> #include <cstdlib> //for atoi #include <stdio.h> //for sprintf using namespace std; int main() { char buf1[] = "597332"; int x = atoi(buf1); cout << x << endl; char buf2[16] = {0}; int ret = sprintf(buf2, "%d", x); cout << buf2 << endl; cout << "number of characters written: " << ret << endl; return 0; }
The output of this program is:
597332 597332 number of characters written: 6
Note: If you can’t bear the absence of itoa, and are interested in writing your own version, a great place to start is with the example defined in Kernighan and Richie’s The C Programming Language.
Here’s another handy post for “Converting numbers to strings and strings to numbers”.