👨‍💻
Guide
Laura's GithubSimon's Github
  • What is this gitbook for?
  • 🛠️Useful tools
    • 🏁Header files
    • 🧱C Structures
    • 🔗Linked Lists (todo)
    • 📄Makefiles
    • 🔄Switch statement
    • 🗃️File descriptors (FD)
  • 🖌️MiniLibX
    • MiniLibX Helper Function
    • MiniLibX Hook Examples
  • 0️⃣ Rank 00
    • Libft
      • 📑LIBC functions
        • ft_isalpha
        • ft_isdigit
        • ft_isalnum
        • ft_isascii
        • ft_isprint
        • ft_strlen
        • ft_memset
        • ft_bzero
        • ft_memcpy
        • ft_memmove
        • ft_strlcpy
        • ft_strlcat
        • ft_toupper
        • ft_tolower
        • ft_strchr
        • ft_strrchr
        • ft_strncmp
        • ft_memchr
        • ft_memcmp
        • ft_strnstr
        • ft_atoi
        • ft_calloc
        • ft_strdup
      • 📑Additional functions
        • ft_substr
        • ft_strjoin
        • ft_strtrim
        • ft_split
        • ft_itoa
        • ft_strmapi
        • ft_striteri
        • ft_putchar_fd
        • ft_putstr_fd
        • ft_putendl_fd
        • ft_putnbr_fd
      • 📑Bonus functions
        • ft_lstnew
        • ft_lstadd_front
        • ft_lstsize
        • ft_lstlast
        • ft_lstadd_back
        • ft_lstdelone
        • ft_lstclear
        • ft_lstiter
        • ft_lstmap
  • 1️⃣ Rank 01
    • Born2beRoot
      • 📠What's a virtual machine ?
      • 📠Install your virtual machine
      • 📠P2P Evaluation - Questions
    • ft_printf
      • ▪️Variadic functions
      • ▪️Building the thing
    • get_next_line
      • ▪️open() & read()
      • ▪️Static variables
      • ▪️Building the thing
      • ▪️Commented solution
  • 2️⃣ Rank 02
    • so_long
      • ▪️Understand so_long
      • ▪️Core concepts
      • ▪️Building the thing
    • pipex
      • ▪️Understand pipex
      • ▪️Functions used
      • ▪️Building the thing
    • minitalk
      • ▪️Understand minitalk
      • ▪️Functions used
      • ▪️Building the thing
    • push_swap
      • ▪️Algorithms
      • ◾Building the thing
    • FdF
      • 🗡️Understand FdF
      • 🗡️Graphics programming
      • 🗡️Building the thing
  • 3️⃣ RANK 03
    • Philosophers
      • ▪️Understand Philosophers
      • ▪️Functions used
      • ▪️Building the thing
    • Minishell
      • ▪️Understand Minishell
      • ▪️Functions
      • ◾Building the thing
  • 4️⃣ RANK 04
    • CPP (00 - 04) (doing)
      • CPP00
      • CPP01
      • CPP02
      • CPP03
      • CPP04 (doing)
    • NetPractice
      • Theory
      • Level 1 & 2
    • MiniRT
      • Understand MiniRT
      • Building the thing
  • 5️⃣ RANK 05
    • CPP (05-09) (to-do)
      • CPP05
      • CPP06 (to-do)
      • CPP07
      • CPP08 (to-do)
      • CPP09 (to-do)
    • Inception (doing)
      • 🕓The basics (Docker, Images, etc...)
      • Project Files
    • webserv (to-do)
  • 6️⃣ rank 06
    • ft_transcendence (to-do)
  • 🛂Exams
    • Exam Rank 02
      • Level 1
        • first_word
        • fizz_buzz
        • *ft_putstr
        • *ft_strcpy
        • *ft_strlen
        • ft_swap
        • repeat_alpha
        • rev_print
        • rot_13
        • rotone
        • search_and_replace
        • ulstr
      • Level 2
        • alpha_mirror
        • camel_to_snake
        • do_op
        • *ft_atoi
        • *ft_strcmp
        • ft_strcspn
        • ft_strspn
        • *ft_strdup
        • ft_strpbrk
        • ft_strrev
        • inter
        • last_word
        • ft_is_power_2
        • max
        • print_bits
        • reverse_bits
        • wdmatch
        • swap_bits
        • union
        • snake_to_camel
      • Level 3
        • add_prime_sum
        • epur_str
        • expand_str
        • ft_atoi_base
        • ft_list_size
        • ft_range
        • ft_rrange
        • hidenp
        • lcm
        • paramsum
        • pgcd
        • print_hex
        • rstr_capitalizer
        • str_capitalizer
        • tab_mult
      • Level 4
        • flood_fil
        • fprime
        • ft_split
        • ft_itoa
        • ft_list_foreach
        • ft_list_remove
        • rev_wstr
        • rotstring
        • sort_int_tab
        • sort_list
    • Exam Rank 03
    • Exam Rank 04
    • Exam Rank 05
      • Module 0
  • 👥Team
Powered by GitBook
On this page
  • Subject
  • Understandable explanation
  • Hints
  • Commented solution

Was this helpful?

  1. 0️⃣ Rank 00
  2. Libft
  3. LIBC functions

ft_atoi

Subject

ATOI(3) (simplified)

NAME
    atoi -- convert ASCII string to integer
SYNOPSIS
    int atoi(const char *str);
DESCRIPTION
    The atoi() function converts the initial portion of the string pointed to by str to int representation.

Understandable explanation

The atoi() function converts a string to its int representation.

Some things that the atoi() function does are not clearly said in the man. I'll quickly list them here.

  • The string passed as parameter may begin with an arbitrary number of whitespaces as determined by isspace(3)

  • After the arbitrary number of whitespaces, there can be one single optional '+' or '-' sign

  • The remainder of the string will be converted to an int, stopping at the first character which is not a valid digit in the given base (in our case we only need to manage base 10, so the valid digits are 0-9)

I talked about the isspace(3) function, what is that function ? It works the same way as the isdigit, isalpha, etc. but returning a non-zero value when the character is one of the following

isspace(3)
  • \t => tabulation

  • \n => new line

  • \v => vertical tabulation

  • \f => form feed

  • \r => carriage return

  • ' ' => space

To make it easier, will be coding the isspace(3) function as a static helper function for our atoi(3) function.

Hints

ft_atoi.c
int    ft_atoi(const char *str)
{
    while (/* character isspace */)
        /* advance in the string */
    if (/* character is + and next character is not - */)
        /* advance in the string */
    if (/* character is - */)
        /* save the sign as negative */
    while (/* there is something in the string and that is a digit 0-9 */)
        /* convert the current digit value to int value */
        /* don't overwrite what we already converted */
    /* multiply the int result by the sign */
    return (/* result */);
}

static int    ft_isspace(int c)
{
    if (/* c is one of the whitespace characters */)
        return (/* non-zero value of your choice */);
    return (0);
}

Commented solution

ft_atoi
ft_atoi.c
#include "libft.h"

int    ft_atoi(const char *str)
{
    int    result;
    int    sign;
    int    i;
    
    result = 0;
    sign = 1;
    i = 0;
    /* here we use our version of the isspace function to check if
     * the current character is a whitespace
     */
    while (ft_isspace(str[i]))
        i++;
    /* checking if the character is a + character and that the next
     * one is not a -
     * we don't have to check if the following character is another +
     * because if the following is also a + it won't enter the following
     * condition that checks for a - character
     * and if it doesn't enter the following condition it will not enter
     * the main while loop that only checks for digits 0-9
     */
    if (str[i] == '+' && str[i + 1] != '-')
        i++;
    /* if the current character is -, we make sign equal to -1 so 
     * we can simply multiply the final result by this sign
     * to get the negative or positive number
     */
    if (str[i] == '-')
    {
        sign = -1;
        i++;
    }
    /* while we are not at the end of the string and the character is 
     * a digit between 0 and 9 
     * we multiply the current result by 10 so we add another digit
     * to the result
     * then we add the decimal value of the current character - 48 to
     * the result. the -48 part comes from the ASCII table. The '0'
     * character as the decimal value 48, and we don't want to add 48 to
     * our int result, but 0, so we substract 48. 
     * Since all digits between 0 and 9 follow each other in the ASCII
     * table, this substract works for every one of them.
     * Then we move to the next character in the string
     */
    while (str[i] && str[i] >= 48 && str[i] <= 57)
    {
        /* take a look under this expandable, I made a clearer example
         * of how this part works
         */
        result *= 10;
	result += str[i] - 48;
	i++;
    }
    /* When we converted every digit to int, we multiply the end result
     * by the sign variable
     * if the number is negative, this means we'll be multiplying by -1
     * therefore getting the negative value of result
     * if the number is positive, since the sign variable was set to 1 at
     * the beginning of the function, we multiply the end result by one,
     * so the result value stays unchanged
     */
    result *= sign;
    return (result);
}

int    ft_isspace(int c)
{
    /* this checks if the character is one of the whitespaces */
    if (c == 9 || c == 10 || c == 11 || c == 12 || c == 13 || c == 32)
        /* we could return c here, if we reach this point the value of 
         * c will be a non-zero value
         */
        return (1);
    return (0);
}
Conversion example
int main(void)
{
    int result;
    
    result = 0;              // result = 0
    result *= 10;            // result = 0
    result += '1' - 48;      // result = 1
    result *= 10;            // result = 10
    result += '5' - 48;      // result = 15
    result *= 10;            // result = 150
    result += '4' - 48;      // result = 154
}

I hope this will help you understand what happens in the while loop of our ft_atoi() function.

Previousft_strnstrNextft_calloc

Last updated 2 years ago

Was this helpful?

📑