Files
42_INT_01_libft/srcs/part2/ft_itoa.c
2019-12-09 22:03:22 +01:00

58 lines
1.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/25 13:59:01 by hulamy #+# #+# */
/* Updated: 2019/12/09 21:25:06 by hulamy ### ########.fr */
/* */
/* ************************************************************************** */
/*
** take an integer and give a string
*/
/*
** #include <libc.h>
**
** char *ft_itoa(int n);
**
** int main(int ac, char **av)
** {
** if (ac == 0)
** return (0);
** else if (ac == 2)
** printf("%s\n",ft_itoa(atoi(av[1])));
** else
** printf("%s\n",ft_itoa(0));
** return 0;
** }
*/
#include "libft.h"
char *ft_itoa(int n)
{
char *str;
int len;
long int nbis;
len = (n < 0) ? 2 : 1;
nbis = n;
while (nbis /= 10)
len++;
nbis = n;
nbis *= (nbis < 0) ? -1 : 1;
if (!(str = (char *)malloc(sizeof(char) * (len + 1))))
return (NULL);
str[len] = '\0';
str[--len] = nbis % 10 + '0';
while (nbis /= 10)
str[--len] = nbis % 10 + '0';
if (n < 0)
str[0] = '-';
return (str);
}