Skip to main content

ft_atoi — String to Integer

Allowed functions: none

Write a function that converts the string argument str to an integer (type int) and returns it. It works much like the standard atoi(const char *str) function.

int	ft_atoi(const char *str);

Solution

Download ft_atoi.c
int ft_atoi(const char *str) {

int result = 0;
int sign = 1;

while (*str == ' ' || (*str >= '\t' && *str <= '\r'))
str++;

if (*str == '+' || *str == '-') {
if (*str == '-')
sign = -1;

str++;
}

while (*str >= '0' && *str <= '9') {
result = result * 10 + *str - '0';
str++;
}

return result * sign;
}

How It Works

Goal: Convert a string representation of a number into an actual integer.

Approach: Skip leading whitespace, detect an optional sign, then build the number digit by digit.

Step by step:

  1. Skip all whitespace characters (spaces and control characters \t through \r).
  2. Check for a + or - sign and store the sign; advance past it.
  3. Loop through consecutive digit characters, accumulating the result: multiply the current result by 10 and add the new digit (*str - '0' converts ASCII to its numeric value).
  4. Return the result multiplied by the sign.

Key concept: ASCII-to-integer conversion using - '0', and handling optional sign prefixes.