From 08bae7751815f2f45044144460db7897ef1c2128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Thu, 17 Oct 2024 17:37:10 +0200 Subject: [PATCH] ft_itoa: initial implementation I wrote this in a single session, with 0 errors on the first try! --- Makefile | 5 ++-- ft_itoa.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ libft.h | 2 ++ 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 ft_itoa.c diff --git a/Makefile b/Makefile index 57b6219..40dd6e8 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ # By: kcolin +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2024/10/14 13:43:59 by kcolin #+# #+# # -# Updated: 2024/10/17 14:12:23 by kcolin ### ########.fr # +# Updated: 2024/10/17 17:07:32 by kcolin ### ########.fr # # # # **************************************************************************** # @@ -38,7 +38,8 @@ SOURCES = ft_isalpha.c \ ft_substr.c \ ft_strjoin.c \ ft_strtrim.c \ - ft_split.c + ft_split.c \ + ft_itoa.c OBJECTS = $(SOURCES:.c=.o) CC = gcc diff --git a/ft_itoa.c b/ft_itoa.c new file mode 100644 index 0000000..7666568 --- /dev/null +++ b/ft_itoa.c @@ -0,0 +1,73 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_itoa.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: kcolin +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2024/10/17 17:08:01 by kcolin #+# #+# */ +/* Updated: 2024/10/17 17:33:18 by kcolin ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" +#include + +static int nb_needed_chars(long num) +{ + int count; + + count = 0; + if (num <= 0) + { + count++; + num = -num; + } + while (num != 0) + { + count++; + num /= 10; + } + return (count); +} + +char *ft_itoa(int n) +{ + long num; + size_t idx; + char *out; + + num = n; + idx = nb_needed_chars(num); + if (num < 0) + num = -num; + out = malloc(idx + 1); + if (out == NULL) + return (NULL); + out[idx--] = '\0'; + while (num > 0) + { + out[idx--] = (num % 10) + '0'; + num /= 10; + } + if (n < 0) + out[idx] = '-'; + if (n == 0) + out[idx] = '0'; + return (out); +} + +/* +#include +#include + +int main(void) +{ + printf("%s\n", ft_itoa(0)); + printf("%s\n", ft_itoa(42)); + printf("%s\n", ft_itoa(-42)); + printf("%s\n", ft_itoa(INT_MAX)); + printf("%s\n", ft_itoa(INT_MIN)); + return (0); +} +*/ diff --git a/libft.h b/libft.h index cdab05f..f00186e 100644 --- a/libft.h +++ b/libft.h @@ -52,4 +52,6 @@ char *ft_strjoin(char const *s1, char const *s2); char *ft_strtrim(char const *s1, char const *set); char **ft_split(char const *s, char c); +char *ft_itoa(int n); + #endif