> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/piscine-life/c04/ft_atoi.md).

# ft\_atoi

**Objective:**

Convert the initial portion of a string pointed to by `str` to its integer representation. The string can contain leading whitespace, an arbitrary number of `+` and `-` signs, and numeric characters.

***

**Turn-in Directory:**

`ex03/`

***

**Files to Turn In:**

`ft_atoi.c`

***

**Allowed Functions:**

None

***

**Prototype:**

```c
int ft_atoi(char *str);
```

***

#### **Detailed Explanation**

The `ft_atoi` function converts a string to an integer. It handles:

* Leading whitespace characters (as determined by `isspace(3)`).
* An arbitrary number of `+` and `-` signs (the sign of the result depends on whether the number of `-` signs is odd or even).
* Numeric characters (digits `0-9`).

The function stops reading the string when it encounters a character that is not a digit.

***

#### **Code Implementation**

```c
int ft_atoi(char *str)
{
    int number;
    int minus;

    minus = 0;
    number = 0;
    while ((*str >= 9 && *str <= 13) || *str == 32)  // Skip leading whitespace
    {
        str++;
    }
    while (*str == '-' || *str == '+')  // Handle signs
    {
        if (*str == '-')
            minus++;
        str++;
    }
    while (*str >= '0' && *str <= '9')  // Convert numeric characters to integer
    {
        number *= 10;
        number += *str - 48;
        str++;
    }
    if (minus % 2 != 0)  // Apply the sign
        return (-number);
    return (number);
}
```

***

#### **Example Usage**

```c
#include <stdio.h>

int ft_atoi(char *str);

int main(void)
{
    printf("Result 1: %d\n", ft_atoi("42"));  // Output: 42
    printf("Result 2: %d\n", ft_atoi("   -123"));  // Output: -123
    printf("Result 3: %d\n", ft_atoi("++567"));  // Output: 567
    printf("Result 4: %d\n", ft_atoi("--789"));  // Output: 789
    printf("Result 5: %d\n", ft_atoi("   +-+-42abc"));  // Output: 0
    printf("Result 6: %d\n", ft_atoi("   -2147483648"));  // Output: -2147483648 (INT_MIN)
    return 0;
}
```

***

#### **Edge Cases to Consider**

1. **Leading Whitespace**:
   * `" 42"` → Returns `42`.
2. **Multiple Signs**:
   * `"++567"` → Returns `567`.
   * `"--789"` → Returns `789`.
   * `"+-+42"` → Returns `-42`.
3. **Negative Numbers**:
   * `"-123"` → Returns `-123`.
   * `" -2147483648"` → Returns `-2147483648` (INT\_MIN).
4. **Invalid Characters**:
   * `"42abc"` → Returns `42` (stops at `'a'`).
   * `"abc42"` → Returns `0` (no valid numeric characters at the start).
5. **Empty String**:
   * `""` → Returns `0`.

***

#### **Limitations of ft\_atoi**

1. **No Overflow Handling**:
   * The function does not handle integer overflow or underflow. If the number is too large or too small to fit in an `int`, the result is undefined.
2. **No Validation of Non-Numeric Characters**:
   * If the string contains non-numeric characters after the number, the function stops processing and returns the number found so far.

***

#### **How It Works**

1. **Skip Leading Whitespace**:
   * The first `while` loop skips any leading whitespace characters (ASCII values 9-13 and 32).
2. **Handle Signs**:
   * The second `while` loop processes any `+` or `-` signs. It counts the number of `-` signs to determine the final sign of the number.
3. **Convert Numeric Characters**:
   * The third `while` loop converts the numeric characters to an integer. It multiplies the current result by 10 and adds the numeric value of the current character (`*str - 48`).
4. **Apply the Sign**:
   * If the number of `-` signs is odd, the result is negated.

***

#### **Key Points to Remember**

1. **Whitespace Handling**:
   * The function skips all leading whitespace characters, as specified in the `isspace(3)` behavior.
2. **Sign Handling**:
   * The function processes multiple `+` and `-` signs and determines the final sign based on the number of `-` signs.
3. **Numeric Conversion**:
   * The function stops processing when it encounters a non-numeric character.
4. **Edge Cases**:
   * The function handles edge cases like `INT_MIN` and strings with invalid characters.

***

#### **Best Practices**

1. **Adhere to the Norm**:
   * Ensure your code follows the **norminette** guidelines (e.g., no more than 25 lines per function, proper indentation, etc.).
   * Run `norminette` on your file to check for compliance.
2. **Test Edge Cases**:
   * Test your function with leading whitespace, multiple signs, negative numbers, and invalid characters.
3. **Avoid Using Library Functions**:
   * Do not use built-in functions like `atoi` from the C standard library. The goal is to implement the functionality yourself.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/piscine-life/c04/ft_atoi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
