-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_atoi.c
94 lines (84 loc) · 2.49 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aschenk <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/21 14:33:52 by aschenk #+# #+# */
/* Updated: 2024/02/21 20:54:42 by aschenk ### ########.fr */
/* */
/* ************************************************************************** */
/*
The atoi() function transforms a string into its corresponding integer
representation.
The string provided as a parameter may start with any number of leading
whitespaces, as determined by isspace(3). Following these whitespaces, there
may be an optional single '+' or '-' sign. The conversion continues until the
first character that is not a valid digit in the specified base is encountered.
For our purposes, where we only need to handle base 10, valid digits: 0-9.
*/
#include "libft.h"
int ft_atoi(const char *nptr)
{
int sign;
int res;
sign = 1;
res = 0;
while (*nptr == ' ' || (*nptr >= 9 && *nptr <= 13))
nptr++;
if (*nptr == '-')
sign = sign * -1;
if (*nptr == '-' || *nptr == '+')
nptr++;
while (*nptr >= '0' && *nptr <= '9')
{
res = res * 10 + *nptr - '0';
nptr++;
}
return (res * sign);
}
/*
#include <stdio.h>
#include <string.h>
int main(void)
{
char int_num[100];
int lib_res;
int my_res;
char test_cases[][100] =
{
"123",
"-123",
" 123",
"123 ",
" 123 ",
" -123 ",
" +123 ",
"",
"abc-123",
" 123abc",
"2147483647",
"-2147483648",
"2147483648",
"-2147483649"
};
printf("=======================\n");
printf("== TESTING FT_ATOI() ==\n");
printf("=======================\n\n");
for (size_t i = 0; i < sizeof(test_cases) / sizeof(test_cases[0]); ++i)
{
strcpy(int_num, test_cases[i]);
lib_res = atoi(int_num);
my_res = ft_atoi(int_num);
printf("Testing: '%s'\n", int_num);
printf("Lib atoi(): %d\n", lib_res);
printf("My ft_atoi(): %d\n", my_res);
if (lib_res == my_res)
printf("OK!\n\n");
else
printf("ERROR!\n\n");
}
return (0);
}
*/