Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an atoi function

Tags:

c

function

atoi

I'm attempting to create my own atoi function. With the following I'm getting a return value of 0. Whatever I change the number variable within the function is what I get as a return value. Any suggestions on modifying the code?

//my atoi function
int atoi_me(char *numstring)
{
    int number = 0;
    while((*numstring >= '0') && (*numstring <= '9'))
    {
        number = (number * 10) + (*numstring - '0');
        numstring++;
    }

    return number;
}

int main()
{
    char *number[MAXSIZE];
    int num;

    printf("Please enter a number:\n");
    scanf("%c", &number);
    num = atoi_me(*number);
    printf("%d", num);
    return 0;
}
like image 858
KryptNick Avatar asked Dec 26 '22 05:12

KryptNick


2 Answers

  1. You're declaring an array of char *, that is, an array of strings, rather than a single string. You probably want:

    char number[MAXSIZE];
    
  2. Your scanf format string is wrong. If you want to read a string, you should use %s. %c reads only a single character.

  3. Your scanf parameter is wrong - pass number itself (or &number[0] if you prefer), not &number.

  4. The parameter you're passing to atoi_me is wrong. Call it with number (or equivalently &number[0]), not *number.

Putting all of that together, you should have a main routine something like this:

int main(void)
{
    char number[MAXSIZE];
    int num;
    printf("Please enter a number: ");
    scanf("%s", number);
    num = atoi_me(number);
    printf("%d\n", num);
    return 0;
} 

Editorial notes: You have a potential buffer overflow with the scanf line. You'd be better off using a function like fgets(3) that makes it easy to protect against that kind of problem.

atoi(3) also traditionally supports negative numbers (with a leading -) and an optional leading + for positive numbers, which your implementation doesn't handle.

like image 118
Carl Norum Avatar answered Jan 07 '23 17:01

Carl Norum


As I thought, the problem is in your call.

Change your main to.

int main()
{
    char number[MAXSIZE];
    int num;

    printf("Please enter a number:\n");
    scanf("%s", number);
    num = atoi_me(number);
    printf("%d", num);
    return 0;
}

Other than this it's not a good idea to use scanf - http://c-faq.com/stdio/scanfprobs.html . In this case you should use fgets.

like image 26
user93353 Avatar answered Jan 07 '23 16:01

user93353