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

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -