From 1d032f7b5e10132abdd29f231241016b6a7d27d7 Mon Sep 17 00:00:00 2001 From: Timo Schmidt Date: Fri, 31 Mar 2023 22:05:56 +0200 Subject: [PATCH] Implemented ft_atoi.c --- ex03/ft_atoi.c | 80 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 70 insertions(+), 10 deletions(-) diff --git a/ex03/ft_atoi.c b/ex03/ft_atoi.c index c64657a..2e5ff51 100644 --- a/ex03/ft_atoi.c +++ b/ex03/ft_atoi.c @@ -6,25 +6,85 @@ /* By: tischmid +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* 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); } /* ////