Reputation: 41
#include<stdio.h>
int ft_atoi(char *str)
{
int i;
int sign;
int val;
int nbr;
i = 0;
sign = 1;
val = 0;
nbr = 0;
while(str[i] != '\0')
{
if (str[i] == '-')
sign = -sign;
i++;
}
i = 0;
while(str[i] >= '0' && str[i] <= '9' && str[i] != '\0')
{
nbr = (int) (str[i] - '0');
val = (val * 10) + nbr;
i++;
}
i++;
return (val * sign);
}
It returns 0 when I try with negative numbers.
Upvotes: 3
Views: 4517
Reputation: 469
you can just str++;
in your if when str is negative
#include <stdio.h>
int ft_atoi(char *str)
{
int i;
int sign;
int val;
int nbr;
i = 0;
sign = 1;
val = 0;
nbr = 0;
while(str[i] != '\0')
{
if (str[i] == '-')
{
sign = -sign;
str++;
}
i++;
}
i = 0;
while(str[i] >= '0' && str[i] <= '9' && str[i] != '\0')
{
nbr = (int) (str[i] - '0');
val = (val * 10) + nbr;
i++;
}
i++;
return (val * sign);
}
Upvotes: 1
Reputation: 29126
After you have scanned the string for minus signs, you reset i
to zero, but str[0]
isn't a valid digit, because it's a minus sign.
You can change the first loop to advance past the first minus sign and the start parsing the numerical value from where the first loop left off:
int ft_atoi(char *str)
{
int i = 0;
int sign = 1;
int val = 0;
while (str[i] == '-') {
sign = -sign;
i++;
}
while(str[i] >= '0' && str[i] <= '9')
{
int nbr = (int) (str[i] - '0');
val = (val * 10) + nbr;
i++;
}
return (val * sign);
}
(There's no need to check that str[i]
isn't the null character, because if it is a minus sign or a digit, it can't be the null character. The check is useful for testing negatives, however, e.g. when testing that some character isn't a minus.)
Upvotes: 2
Reputation: 9804
the second while loop breaks if str[0]
is '-'
.
while(str[i] != '\0')
{
if (str[i] == '-')
sign = -sign;
i++;
}
should be
if (str[0] == '-')
{
sign = -1;
str++;
}
Upvotes: 4