How can I convert numbers to strings (the opposite of atoi)? Is there an itoa function?

Q

How can I convert numbers to strings (the opposite of atoi)? Is there an itoa function?

✍: Guest

A

Just use sprintf:
sprintf(string, "%d", number);
(Don't worry that sprintf may be overkill, potentially wasting run time or code space; it works well in practice.) You can obviously use sprintf to convert long or floating-point numbers to strings as well (using %ld or %f); in other words, sprintf can also be thought of as the opposite of atol and atof. In addition, you have quite a bit of control over the formatting. (It's for these reasons that C supplies sprintf as a general solution, and not itoa.)
If you simply must write an itoa function, here are some things to consider:
* There is a sample implementation in K&R.
* You'll have to worry about return buffer allocation;
# A naïve implementation usually doesn't handle the most-negative integer (INT_MIN, usually -32,768 or -2,147,483,648) properly.

2015-08-24, 1697👍, 0💬