c - Why doesn't my atoi implementation work with negative numbers? -
#include<stdio.h> int ft_atoi(char *str) { int i; int sign; int val; int nbr; = 0; sign = 1; val = 0; nbr = 0; while(str[i] != '\0') { if (str[i] == '-') sign = -sign; 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 try negative numbers.
the second while loop breaks if str[0]
'-'
.
while(str[i] != '\0') { if (str[i] == '-') sign = -sign; i++; }
should be
if (str[0] == '-') { sign = -1; str++; }
Comments
Post a Comment