mardi 1 novembre 2016

why is my string being read this way?

I am trying to recreate atoi and I'm wondering why my function works. I ended up changing it to str[i] for the three top statements because it made sense to me, but it passed everything I threw at it.

i = 0;
result = 0;
negative = 1;
if (str[0] == '-')
{
    negative = -1;
    i++;
}
if (str[0] == '+')
    i++;
while (str[0] <= ' ')
    i++;
while (str[i] != '\0')
    if (str[i] >= '0' && str[i] <= '9')
    {
        result = result * 10 + str[i] - '0';
        ++i;
    }
return (result * negative);

Aucun commentaire:

Enregistrer un commentaire