maxishell
Implementation of a shell for Linux-like systems
Loading...
Searching...
No Matches
ft_itoa.c
Go to the documentation of this file.
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* ft_itoa.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: rmikhayl <rmikhayl@student.42london.c +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2023/12/17 17:25:28 by rmikhayl #+# #+# */
9
/* Updated: 2023/12/17 17:25:28 by rmikhayl ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
13
#include "
libft.h
"
14
15
/* *************************** ft_itoa ************************************** */
16
/* Allocates and returns a string representing the integer 'n'. */
17
/* Handles negative numbers. Returns NULL on allocation failure. */
18
/* */
19
/* In layman's terms: It converts an integer into a string of characters, */
20
/* taking care of whether the number is positive or negative. */
21
/* ************************************************************************** */
22
23
static
int
count_digits
(
int
n)
24
{
25
int
count;
26
27
count = 0;
28
if
(n <= 0)
29
count = 1;
30
else
31
count = 0;
32
while
(n != 0)
33
{
34
count++;
35
n /= 10;
36
}
37
return
(count);
38
}
39
40
char
*
ft_itoa
(
int
n)
41
{
42
int
len;
43
char
*str;
44
45
if
(n == INT_MIN)
46
return
(
ft_strdup
(
"-2147483648"
));
47
if
(n == 0)
48
return
(
ft_strdup
(
"0"
));
49
len =
count_digits
(n);
50
str = (
char
*)malloc(len + 1);
51
if
(!str)
52
return
(NULL);
53
str[len--] =
'\0'
;
54
if
(n < 0)
55
{
56
str[0] =
'-'
;
57
n = -n;
58
}
59
while
(n)
60
{
61
str[len--] = n % 10 +
'0'
;
62
n /= 10;
63
}
64
return
(str);
65
}
count_digits
static int count_digits(int n)
Definition
ft_itoa.c:23
ft_itoa
char * ft_itoa(int n)
Definition
ft_itoa.c:40
libft.h
ft_strdup
char * ft_strdup(const char *s)
Definition
ft_strdup.c:23
lib
libft
src
ft_itoa.c
Generated by
1.9.8