ft_itoa: initial implementation
I wrote this in a single session, with 0 errors on the first try!
This commit is contained in:
parent
d1b5c7b687
commit
08bae77518
3 changed files with 78 additions and 2 deletions
5
Makefile
5
Makefile
|
|
@ -6,7 +6,7 @@
|
|||
# By: kcolin <marvin@42.fr> +#+ +:+ +#+ #
|
||||
# +#+#+#+#+#+ +#+ #
|
||||
# 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
|
||||
|
||||
|
|
|
|||
73
ft_itoa.c
Normal file
73
ft_itoa.c
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/* ************************************************************************** */
|
||||
/* */
|
||||
/* ::: :::::::: */
|
||||
/* ft_itoa.c :+: :+: :+: */
|
||||
/* +:+ +:+ +:+ */
|
||||
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2024/10/17 17:08:01 by kcolin #+# #+# */
|
||||
/* Updated: 2024/10/17 17:33:18 by kcolin ### ########.fr */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
#include "libft.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
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 <stdio.h>
|
||||
#include <limits.h>
|
||||
|
||||
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);
|
||||
}
|
||||
*/
|
||||
2
libft.h
2
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue