71 lines
1.9 KiB
C
Executable file
71 lines
1.9 KiB
C
Executable file
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_atoi.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/10/14 18:37:49 by thrieg #+# #+# */
|
|
/* Updated: 2025/02/16 19:02:53 by thrieg ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
#include <errno.h>
|
|
|
|
static int ft_is_space(char c)
|
|
{
|
|
if (c == '\t' || c == '\n' || c == '\v'
|
|
|| c == '\f' || c == '\r' || c == ' ')
|
|
return (1);
|
|
else
|
|
return (0);
|
|
}
|
|
|
|
static int ft_convert_to_int(const char *str, int sign, int *overflow_flag)
|
|
{
|
|
int value;
|
|
|
|
value = 0;
|
|
while (ft_isdigit(*str))
|
|
{
|
|
if (sign == 1)
|
|
{
|
|
if (value > (INT_MAX - (*str - '0')) / 10)
|
|
if (overflow_flag)
|
|
*overflow_flag = 1;
|
|
value = value * 10 + (*str - '0');
|
|
}
|
|
else
|
|
{
|
|
if (value < (INT_MIN + (*str - '0')) / 10)
|
|
if (overflow_flag)
|
|
*overflow_flag = 1;
|
|
value = value * 10 - (*str - '0');
|
|
}
|
|
str++;
|
|
}
|
|
return (value);
|
|
}
|
|
|
|
int ft_atoi(const char *nptr, int *overflow_flag)
|
|
{
|
|
int sign;
|
|
|
|
if (overflow_flag)
|
|
*overflow_flag = 0;
|
|
while ((*nptr != '\0') && ft_is_space(*nptr))
|
|
{
|
|
nptr++;
|
|
}
|
|
sign = 1;
|
|
if ((*nptr != '\0') && (*nptr == '-' || *nptr == '+'))
|
|
{
|
|
if (*nptr == '-')
|
|
sign = -sign;
|
|
nptr++;
|
|
}
|
|
if (!ft_isdigit(*nptr))
|
|
return (0);
|
|
return (ft_convert_to_int(nptr, sign, overflow_flag));
|
|
}
|