[DGD] atoi

Par Winzell zell at skotos.net
Tue Feb 3 17:20:55 CET 2004


Robert Forshaw wrote:
> Does anyone here have a working atoi function in lpc that they can show 
> me? I tried making one:

Felix' suggestion causes an error if 'str' is not in fact an integer; if 
you want something friendlier, you can use sscanf() -- e.g.

static int atoi(string str) {
   int n;

   if (sscanf(strip_whitespace(str), "%d", n) > 0) {
     return n;
   }
   /* somehow signal the problem, e.g. return 0, error(), whatever */
}


>    for(count = strlen(str) - 1; count < 0; count--)
>      {
>          if(str[count] < '0' || str[count] > '9')
>                continue;
> 
>          result +=
>            (str[count] - NUMERIC_MODIFIER) * int_pow(10,
>                ((strlen(str) - count) + 1));
>      }
>    if(result > 10)
>          return result / 10;
>    return 0;
> }

If you want to do it this way, that's fine too. Your function is very 
lenient, though -- it tries to parse 'foo1bar' to 1, which is rather a 
stretch. I'd just error() if there are illegal characters, e.g.


   str = strip_whitespace(str);

   for (i = 0; i < strlen(str); i ++) {
     if (str[i] < '0' || str[i] > '9') {
       error("not a valid integer");
     }
     result = (result * 10) + (str[i] - '0');
   }
   return result;
_________________________________________________________________
List config page:  http://list.imaginary.com/mailman/listinfo/dgd



More information about the DGD mailing list