I am trying to write a c code that mulplies two numbers and I wrote a custom atoi() function to convert char to int. I tried running the exe file with the following arguments ./exe 2 3 but it giving me a result of 0 instead of 6 and I can't seem to find where the bug in my code is coming from.
here is a snippet of me code
int myatoi(char* str)
{
int i = 0, result = 0, sign = 1, flag;
/** Chheck for whitespce*/
while (str[i] == ' ')
i++;
/**Check for sign of the first num*/
if (str[i] == '-')
{
sign = -1;
i++;
}
for (; str[i] !='\0'; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
result = result * 10 + (str[i] - '0');
flag = 1;
if (str[i + 1] < '0' || str[i + 1] > '9')
{
flag = 0;
break;
}
}
}
if (flag == 0)
return (0);
return (sign * result);
}
int main(int argc, char *argv[])
{
int i, result = 1;
if (argc < 2)
{
printf("Error\n");
return (1);
}
for (i = 1; i < argc; i++)
{
result = result * myatoi(argv[i]);
}
printf("%d\n", result);
return (0);
}