w3resource

C Language: Custom atoi() function

C - Implementing a custom atoi() function.

The atoi() function is used to convert a character string to an integer value.

Code:

# include <stdio.h>

int my_atoi(const char *str) {
    int result = 0;
    int sign = 1;
    int i = 0;

    // Check for leading sign character
    if (str[0] == '-') {
        sign = -1;
        i++;
    }
    else if (str[0] == '+') {
        i++;
    }

    // Convert digits to integer value
    while (str[i] != '\0') {
        if (str[i] < '0' || str[i] > '9') {
            break;
        }
        result = result * 10 + (str[i] - '0');
        i++;
    }

    return sign * result;
}

int main() {
    const char *str1 = "-1234";
    int result = my_atoi(str1);
    printf("Converted integer: %d\n", result);
    const char *str2 = "1234";
    result = my_atoi(str2);
    printf("\nConverted integer: %d\n", result);
    return 0;
}

Output:

Converted integer: -1234

Converted integer: 1234

The my_atoi() function takes a string as input and returns the corresponding integer value. It checks for a leading sign character and converts the remaining digits to an integer value.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/c-snippets/implementing-custom-atoi-function-in-c.php