Implementing the itoa() function in C / C++ With Examples

In this article, we’ll take a look at implementing the itoa() function in C/C++.

This is a useful utility function which converts an integer into a null-terminated string.

However, it isn’t supported natively by most compilers, as it is not a part of the C standard.

Therefore, let’s take a look at using this function, by implementing it ourselves!.

Basic Syntax of the itoa() function in C/C++

While this function may be available in some compilers, there is no function as such, in most of them.

The itoa() function takes in an integer num, and stores it into buffer. It also has an optional parameter base, which converts it into the appropriate base.

By default, base is set to 10 (decimal base).

After populating buffer, it returns a pointer to the first character of buffer, if the conversion is successful. Otherwise, it returns NULL.

Since there isn’t any default itoa() function in most common C compilers, let’s implement it!


Implementing the itoa() function in C / C++

We’ll take a number, and convert it to a string. We’ll consider both positive and negative integers, and see how itoa() handles them.

Although some websites may have implemented itoa() by evaluating the digits from right to left and then reversing the string, we’ll use a different approach. t

We’ll evaluate the digits from left to right, with the help of certain function from the <math.h> library.

We’ll follow the below procedure:

  • Find the number of digits of num. If num is positive, we know that the number of digits will be floor(log(num, base)) + 1. (Hint: This is pretty easy to derive using logarithms).
  • If num is negative, we will only consider the case where base = 10, since we may need to use separate algorithms to evaluate for any base. We need to put the minus sign as the first digit!
  • Start from the leftmost (highest) digit of num, and keep adding the value to the buffer.

The complete program is shown below. You may be able to understand this better by reading through the code!

Output

NOTE: If you’re compiling with gcc, use the -lm flag to include the math library.

Indeed, we were able to get it working. Not only did this work for integers, but only for other bases too!


Conclusion

Hopefully you were able to get an understanding to converting integers to strings using itoa(), and possibly even implemented one yourself, using this guide!

For similar content, do go through our tutorial section on C programming


By admin

Leave a Reply

%d bloggers like this: