My code isn't giving the output I want.. I want to convert a string to a number and when it encounters any other special character apart from numeric values, it should stop and print out the digit. But even when I add a break statement, it just returns 0.
#include <stdio.h>
int _atoi(char *s)
{
int i = 0;
int sign;
int result;
result = 0;
sign = 1;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == '-')
{
sign = -1;
i++;
}
else if (s[i] == '+')
{
sign = 1;
i++;
}
else if (s[i] == ' ' || s[i] == '\t')
{
i++;
}
if (s[i] >= 48 && s[i] <= 57)
{
result = result * 10 + s[i] - 48;
}
}
return (sign * result);
}
int main (void)
{
int nb;
nb = _atoi("---++++ -++ Sui - te - 402 #cisfun 11 :)");
printf("%d\n", nb);
return (0);
}
It's supposed to print only 402, but it prints 11 after wards.
This is the code. Just like a custom atoi function.