first commit of v2 ft_printf
This commit is contained in:
62
42-libft/ft_itoa.c
Normal file
62
42-libft/ft_itoa.c
Normal file
@@ -0,0 +1,62 @@
|
||||
/* ************************************************************************** */
|
||||
/* */
|
||||
/* ::: :::::::: */
|
||||
/* ft_itoa.c :+: :+: :+: */
|
||||
/* +:+ +:+ +:+ */
|
||||
/* By: dgaillet <dgaillet@student.42.fr> +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2025/11/07 13:06:35 by dgaillet #+# #+# */
|
||||
/* Updated: 2025/11/12 14:20:16 by dgaillet ### ########lyon.fr */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
#include "libft.h"
|
||||
|
||||
static size_t count_digits(int n)
|
||||
{
|
||||
size_t size;
|
||||
|
||||
size = 0;
|
||||
if (n <= 0)
|
||||
size++;
|
||||
while (n)
|
||||
{
|
||||
n /= 10;
|
||||
size++;
|
||||
}
|
||||
return (size);
|
||||
}
|
||||
|
||||
static void insert_char(char *str, unsigned int nbr, size_t index)
|
||||
{
|
||||
while (nbr)
|
||||
{
|
||||
str[index--] = nbr % 10 + '0';
|
||||
nbr /= 10;
|
||||
}
|
||||
}
|
||||
|
||||
char *ft_itoa(int n)
|
||||
{
|
||||
unsigned int nbr;
|
||||
char *str;
|
||||
size_t size;
|
||||
|
||||
nbr = n;
|
||||
if (n < 0)
|
||||
nbr = n * -1;
|
||||
size = count_digits(n);
|
||||
str = malloc(sizeof(char) * (size + 1));
|
||||
if (!str)
|
||||
return (NULL);
|
||||
str[size] = '\0';
|
||||
if (nbr == 0)
|
||||
str[0] = '0';
|
||||
else
|
||||
{
|
||||
if (n < 0)
|
||||
str[0] = '-';
|
||||
insert_char(str, nbr, size - 1);
|
||||
}
|
||||
return (str);
|
||||
}
|
||||
Reference in New Issue
Block a user