Fog Creek Software
Discussion Board




atoi

I don't think that the left to right direction solution to atoi posted on this site is correct.

Given the string 'xxxx00120x3xx.0xx' I would expect the answer to be 120 (and my own code that I wrote quickly without reference to anything else) returns 120. The example code however returns zero.

My code is : (and yes I know its bulky)

int myatoi(char *pStr)
{
    int  nResult          = 0;
    bool bProcessingDigits = false;
    char cCurrentChar;
    
    while ('\0' != (cCurrentChar = *pStr++))
    {
        if (cCurrentChar >= '0' && cCurrentChar <= '9')
        {
            if (nResult > 0 || cCurrentChar > '0')
            {
                nResult *= 10;
                nResult += int(cCurrentChar - '0');
            }

            bProcessingDigits = true;
        }
        else if (bProcessingDigits)
        {
            return nResult;
        }
    }

    return nResult;
}

Ximon Eighteen
Sunday, February 17, 2002

stdlib atoi returns 0 for the string you specified.

Michael H. Pryor
Sunday, February 17, 2002

Hmmm in that case I concede that the given solution on this site would be "correct" but I find the value returned by atoi then to be somewhat suspect.

Ximon Eighteen
Tuesday, February 19, 2002

Personally, if I ever got '120' back from any atoi function that received 'xxxx00120x3xx.0xx' as input, I would not trust it.

First, the input string is clearly not an integer. There are integers in there, but if I asked a normal person "what number is that?" they would look at me oddly. And atoi should look at me oddly too.

In fact, I would prefer that atoi raise an exception given that input, as the string certainly does not represent zero, and most likely there is a bug somewhere else feeding crap to atoi that needs fixing. :-)

My two cents.

Mike Weber
Tuesday, February 19, 2002

*  Recent Topics

*  Fog Creek Home