-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_atoi.c
96 lines (79 loc) · 2.66 KB
/
ft_atoi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amait-ou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/30 17:19:53 by amait-ou #+# #+# */
/* Updated: 2023/06/27 18:14:52 by amait-ou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
"ft_atoi" is the opposite of "ft_itoa" since this one converts from a string
to integer.
Ps: if you want to know why some of my functions here are static ones.
feel free to read the comment I wrote in "libft.h"
the first function is "contain(char *s, int c)" which takes two params,
the first one is "*s" which is a pointer to an array of characters
meanwhile, the second is "c" which is a character.
the main role of the functions is to perform a linear search algorithm
by looping over "s" nTimes and returns true if the "c" was found otherwise
it returns false.
the second and third functions are just helpers to detect spaces
and numbers within my string and both of them rely on the
"contain(char *s, int c)" function
here is the formula that would help us convert from "char" to "int"
integer = integer * 10 + character - 48
we assign the "s" with "1" This variable helps us detect
if there is a negative sign within the "str" parameter if so
that "1" would be "-1" and the result at the end would be
negative.
whenever there is a space the pointer will be one step ahead
if the sign is negative and equal to '-' the "s" will be "-1"
as mentioned before
finally, perform the formula on the first set of numbers and return
an integer (result * sign)
*/
static int contain(char *s, char c)
{
while (*s)
{
if (*s == c)
return (1);
++s;
}
return (0);
}
static int spaces(char c)
{
return (contain("\t\n\v\f\r ", c));
}
static int signs(char c)
{
return (contain("-+", c));
}
int ft_atoi(const char *str)
{
char *p;
int s;
int r;
p = (char *)str;
s = 1;
r = 0;
while (spaces(*p))
++p;
if (signs(*p))
{
if (*p == '-')
s *= -1;
++p;
}
while (*p >= '0' && *p <= '9')
{
r = r * 10 + *p - 48;
++p;
}
return (r * s);
}