diff --git a/Makefile b/Makefile index a78efef..219982e 100644 --- a/Makefile +++ b/Makefile @@ -67,8 +67,10 @@ SRCS = ft_memset.c \ \ ft_atoi.c \ ft_atol.c \ + ft_atof.c \ ft_itoa.c \ ft_utoa.c \ + ft_atoibase.c \ \ ft_putchar.c \ ft_putstr.c \ @@ -94,7 +96,6 @@ SRCS = ft_memset.c \ ft_lstcopy.c \ \ ft_any.c \ - ft_atoibase.c \ ft_convertbase.c \ ft_convertbase_free.c \ ft_foreach.c \ diff --git a/includes/libft.h b/includes/libft.h index 4d4d826..585e735 100644 --- a/includes/libft.h +++ b/includes/libft.h @@ -43,6 +43,7 @@ size_t ft_strlcat(char *dst, const char *src, size_t size); char *ft_strnstr(const char *b, const char *l, size_t s); int ft_atoi(const char *str); long ft_atol(const char *str); +double ft_atof(const char *str); void *ft_calloc(size_t count, size_t size); char *ft_strdup(const char *s1); diff --git a/srcs/ft_atof.c b/srcs/ft_atof.c new file mode 100644 index 0000000..ab8ecbe --- /dev/null +++ b/srcs/ft_atof.c @@ -0,0 +1,42 @@ +#include +#include "libft.h" + +double ft_atof(const char *str) +{ + double nbr; + int i; + int negatif; + double fraction; + + i = 0; + negatif = 1; + nbr = 0.0; + fraction = 1.0; + + // Skip leading whitespace + while ((str[i] == ' ') || (str[i] > 8 && str[i] < 14)) + i++; + + // Handle optional sign + if (str[i] == '-') + negatif = -1; + if (str[i] == '+' || str[i] == '-') + i++; + + // Parse integer part + while (str[i] >= '0' && str[i] <= '9') + nbr = nbr * 10.0 + (str[i++] - '0'); + + // Parse fractional part if '.' is present + if (str[i] == '.') + { + i++; + while (str[i] >= '0' && str[i] <= '9') + { + fraction /= 10.0; + nbr += (str[i++] - '0') * fraction; + } + } + + return (nbr * negatif); +} diff --git a/srcs/ft_atoi.c b/srcs/ft_atoi.c index 8d34949..4c74378 100644 --- a/srcs/ft_atoi.c +++ b/srcs/ft_atoi.c @@ -12,22 +12,29 @@ #include "libft.h" -int ft_atoi(const char *str) +int ft_atoi(const char *str) { - long nbr; - int i; - int negatif; + long nbr; + int i; + int negatif; i = 0; negatif = 1; nbr = 0; + + // Skip leading whitespace while ((str[i] == ' ') || (str[i] > 8 && str[i] < 14)) i++; + + // Handle optional sign if (str[i] == '-') negatif = -1; if (str[i] == '+' || str[i] == '-') i++; + + // parse integer while (str[i] >= '0' && str[i] <= '9') nbr = nbr * 10 + (str[i++] - '0'); + return (nbr * negatif); } diff --git a/srcs/ft_atol.c b/srcs/ft_atol.c index 1bf87cf..817d26c 100644 --- a/srcs/ft_atol.c +++ b/srcs/ft_atol.c @@ -1,22 +1,29 @@ #include "libft.h" -long ft_atol(const char *str) +long ft_atol(const char *str) { - long long nbr; - int i; - int negatif; + long long nbr; + int i; + int negatif; i = 0; negatif = 1; nbr = 0; + + // Skip leading whitespace while ((str[i] == ' ') || (str[i] > 8 && str[i] < 14)) i++; + + // Handle optional sign if (str[i] == '-') negatif = -1; if (str[i] == '+' || str[i] == '-') i++; + + // parse integer while (str[i] >= '0' && str[i] <= '9') nbr = nbr * 10 + (str[i++] - '0'); + return (nbr * negatif); }