ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-252 min read

Implement your own atoi (ASCII to Integer) function in C from scratch. Handle leading whitespace, positive/negative signs, and integer overflow.

What is atoi in C?

The atoi() function in <stdlib.h> parses a C character string and converts its initial numeric characters into a signed 32-bit int.

Conversion Rules:

  1. Discard leading whitespace (' ', '\t', '\n').
  2. Parse an optional sign character ('+' or '-').
  3. Accumulate consecutive numeric digits: res = (res * 10) + (str[i] - '0').
  4. Stop on the first non-numeric character and guard against overflow.

C Source Code

c (ISO Standard)
#include <stdio.h>
#include <ctype.h>
#include <limits.h>

int customAtoi(const char *str) {
    if (str == NULL) return 0;

    int i = 0;
    while (isspace((unsigned char)str[i])) {
        i++;
    }

    int sign = 1;
    if (str[i] == '+' || str[i] == '-') {
        if (str[i] == '-') sign = -1;
        i++;
    }

    long long result = 0;
    while (isdigit((unsigned char)str[i])) {
        int digit = str[i] - '0';

        /* Guard against 32-bit integer overflow */
        if (result > (INT_MAX - digit) / 10) {
            return (sign == 1) ? INT_MAX : INT_MIN;
        }

        result = (result * 10) + digit;
        i++;
    }

    return (int)(result * sign);
}

int main() {
    const char *inputs[] = {"  42", "   -987abc", "+12345", "9999999999999", "words 123"};
    int count = sizeof(inputs) / sizeof(inputs[0]);

    for (int i = 0; i < count; i++) {
        printf("Input: %-20s -> Parsed Int: %d\n", inputs[i], customAtoi(inputs[i]));
    }

    return 0;
}

Sample Output

text (ISO Standard)
Input:   42                 -> Parsed Int: 42
Input:    -987abc           -> Parsed Int: -987
Input: +12345               -> Parsed Int: 12345
Input: 9999999999999        -> Parsed Int: 2147483647
Input: words 123            -> Parsed Int: 0

Complexity Analysis

  • Time Complexity: O(n) single scan of the prefix digits.
  • Space Complexity: O(1) constant auxiliary memory.

Related C Examples & Tutorials