prev up next   top/contents search

comp.lang.c FAQ list · Question 13.1

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

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.) See also the examples in the answer to question 7.5a, and also questions 8.6 and 12.21.

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:

See also questions 12.21 and 20.10.

References: K&R1 Sec. 3.6 p. 60
K&R2 Sec. 3.6 p. 64

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North