Search code examples
atoirecreate

Trying to recreate function atoi


I've problem in recoding function atoi. Here is the code (just function body):

int atoi2(const char *s) {
    int i, sum = 0;
    for (i = 0; isdigit('*s') == 1; s++) {
        sum = (sum * 10) + *s;
        i++;
    }
    return sum;
}

Whenever i call function within parameter as string (like "12345"), i just get the 0. Seems like it passes the for loop.

Meanwhile, yes i used the header

#include<ctype.h>

for using function int isdigit(int).


Solution

  • Your code has two problems, one of which I hoped my comment would eliminate, so you could find the other one. First of all, you always call isdigit with the same value, instead of the current character in the string. That is fixed by removing the single quotes around *s. Secondly, you never actually do any conversion from the character to the number. For this, a little bit of knowledge about ascii is necessary (and some double checking if the standard is on your side: How to convert char to integer in C?). With those two corrections, your code should look like this and actually work:

    int atoi2(const char *s) {
        int i, sum = 0;
        for (i = 0; isdigit(*s); s++) {
            sum = (sum * 10) + (*s - '0');
            i++;
        }
        return sum;
    }