Implemented ft_atoi.c

This commit is contained in:
Timo Schmidt 2023-03-31 22:05:56 +02:00
parent cd7c681fc6
commit 1d032f7b5e
1 changed files with 70 additions and 10 deletions

View File

@ -6,25 +6,85 @@
/* By: tischmid <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/27 19:51:48 by tischmid #+# #+# */
/* Updated: 2023/03/28 14:39:34 by tischmid ### ########.fr */
/* Updated: 2023/03/31 21:58:42 by tischmid ### ########.fr */
/* */
/* ************************************************************************** */
int ft_isspace(char c)
unsigned int char_count(const char *str, char c)
{
return (c == ' '
|| c == '\t'
|| c == '\n'
|| c == '\r'
|| c == '\f'
|| c == '\v');
unsigned int count;
count = 0;
while (*str)
{
if (*str == c)
++count;
++str;
}
return (count);
}
// Return 0 if the base is invalid or the length of the base otherwise
unsigned int is_valid_base(const char *base)
{
unsigned int size;
size = 0;
while (*base)
{
if (*base == '+' || *base == '-' || *base == ' ')
return (0);
if (char_count(base, *base) > 1)
return (0);
++size;
++base;
}
if (size < 2)
return (0);
return (size);
}
int char_index(const char *str, const char c)
{
int idx;
idx = 0;
while (*str)
{
if (*str++ == c)
return (idx);
++idx;
}
return (-1);
}
int ft_atoi(char *str)
{
while (ft_isspace(*str))
int sign;
int abs;
int index_in_base;
unsigned int base_len;
abs = 0;
sign = 1;
base_len = is_valid_base("0123456789");
if (!base_len)
return (0);
while (*str == ' ' || *str == '\t'
|| *str == '\n' || *str == '\r'
|| *str == '\f' || *str == '\v')
++str;
return (0);
while (*str == '+' || *str == '-')
if (*str++ == '-')
sign *= -1;
index_in_base = char_index("0123456789", *str);
while (index_in_base >= 0)
{
abs = abs * base_len + index_in_base;
++str;
index_in_base = char_index("0123456789", *str);
}
return (sign * abs);
}
/* ////