2

I was trying to write my own implementation of the atoi() function, and tried two different codes:

#include <stdio.h>
#include <string.h>

int myatoi(const char *string);

int main(int argc, char* argv[])
{
    printf("\n%d\n", myatoi("str"));
    getch();

    return(0);
}  

int myatoi(const char *string){
    int i;
    i=0;
    while(*string)
    {
        i=(i<<3) + (i<<1) + (*string - '0');
        string++;
        // Don't increment i!
    }
    return i;
}

And

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int x;
    gets(str);
    printf("%d",myatoi(str));
}

int myatoi(char *str) {

    int res =0;
    int i;

    for (i = 0; str[i]!= '\0';i++) {
        res = res*10 + str[i] - '0';
    }
    return res;
}

Both these cases work fine for input e.g. 1999.

But if by chance I am passing user input e.g. "abcd", it is returning some numeric value. I tried it with the original atoi() and it returns 0 for such cases.

Can someone please explain to me how to handle non-numeric input through atoi().

MC93
  • 791
  • 6
  • 14
rose
  • 162
  • 1
  • 1
  • 13

2 Answers2

6

You should use isdigit() to see if the next character is a (decimal) digit or not, and stop when it fails.

You also need to check for, and handle, leading minus sign(s) to indicate a negative number. Not sure if e.g. --12 is valid with atoi() or not, probably not.

Also please don't micro-optimize multiplies like that, it's not the 90s any more. :)

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 2
    Note: `atoi()` handles the optional single leading `-` _and_ `+`; `--12` is not valid. – chux - Reinstate Monica Sep 03 '15 at 14:35
  • Thanks @unwind : atoi() handles only single - and + sign ,If i am passing --12 or ++12 ,It is returning 0. – rose Sep 03 '15 at 14:42
  • 1
    Looking over [atoi — how to identify the difference between zero and error?](http://stackoverflow.com/questions/8871711/atoi-how-to-identify-the-difference-between-zero-and-error), it appears on errant input like `"abcd"`, the result is undefined behavior. So using `isdigit()` helps OP's code act like OP's `aoti()`, but is not required per spec. – chux - Reinstate Monica Sep 03 '15 at 15:32
0

In your own myatoi() function, use isdigit() to check every index value of the incoming pointer, and return a 0 as soon as isdigit() itself returns 0.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261