C Programming

How to Use Itoa Function in C

The C programming language was launched over five decades ago. Since then, it has gained immense popularity in the programming world. It outstands the other languages due to its features including structural simplicity, functions, portability, efficient memory management, etc. Despite having various other features, functions in C are the most prominent assets that assist many users in writing the robust code snippets.

Furthermore, itoa is a widely used non-standard function that acts as a data type converter. It takes the data type int as input and converts it to a string. However, many of you do not know its usage. Therefore, this guide concisely explains how to use the itoa function in C with no hassle.

How to Use the Itoa Function in C

Let’s start with the basics. Here is the simple syntax for the itoa function:

int main() {

    int num = 12345;
    char str[20];
    itoa(num, str, 10);
    printf("Integer: %d\nString: %s\n", num, str);
    return 0;


}

In the given program, the details are as follows:

  1. num is the integer
  2. str is the character
  3. 10 is the bass

Now, let’s move forward, write a program, and implement the itoa function. For example, we need to write a program to change the entered numbers into the string.

#include <stdio.h>

#include <stdlib.h>

void itoa(int num, char *str, int base) {

    int i = 0;
    int isNegative = 0;

    if (num == 0) {
        str[i++] = '0';
        str[i] = '\0';
        return;
    }


    if (num < 0 && base != 10) {

        isNegative = 1;
        num = -num;
    }

    while (num != 0) {
        int rem = num % base;

        str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';

        num = num / base;
    }

    if (isNegative && base == 10)
        str[i++] = '-';

    str[i] = '\0';

    int start = 0;
    int end = i - 1;


    while (start < end) {

        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

int main() {
    int num;
    printf("Enter an integer: ");
   
    if (scanf("%d", &num) != 1) {
        fprintf(stderr, "Invalid input. Please enter an integer.\n");
        return EXIT_FAILURE;
    }

    int max_size = snprintf(NULL, 0, "%d", num) + 1;
    char *str = (char *)malloc(max_size);

    if (str == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return EXIT_FAILURE;
    }


    itoa(num, str, 10);

    printf("Integer: %d\nString: %s\n", num, str);

    free(str);

    return 0;


}

In the previous program, itoa (int num, char *str, int base) is the itoa function. Moreover, the following syntax directly assigns zero to the result when the input number is also zero:

if (num == 0) {

    str[i++] = '0';
    str[i] = '\0';
    return;


}

When the input number is negative and the base is also not 10, the following program lines will set the negative flag:

if (num < 0 && base != 10) {

    isNegative = 1;
    num = -num;

The following loop processes all the digits and converts them to a corresponding character. Hence, for bases that are greater than 10, the program uses the letters “a” to “f” for the digits 10 to 15.

}

while (num != 0) {

    int rem = num % base;

    str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';

    num = num / base;
   
}

When the number is originally negative and the base is 10, the program will append the negative sign to a result string.

if (isNegative && base == 10)

    str[i++] = '-';

The following lines terminate the result string and then reverse it as the digits are obtained in reverse order during the conversion process:

str[i] = '\0';

// Reverse the string

int start = 0;

int end = i - 1;

while (start < end) {

    char temp = str[start];
    str[start] = str[end];
    str[end] = temp;
    start++;
    end--;


}

Hence, the program takes the integer as the input and allocates the memory for the string representation. After that, it calls itoa to convert the integer to the string and prints the original integer. Finally, it frees the allocated memory. For example, let’s give a number to the program:

However, if you enter a non-integer number, the program will show the following result:

Conclusion

This is how you can easily implement and use the itoa function in C. We used a detailed example that contains multiple functions to convert the integer to string. Remember, it is only an example, but you can combine the itoa function with various functions to write amazing programs.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.