How to use atoi() and how to make own atoi() ?

atoi implementation in c

This blog post teaches you how to use the atoi() function and how to implement your own atoi function in C.

The atoi() function converts the numeric string to the int representation. It takes a string as an argument and returns its integer value. Let’s see the syntax of the atoi().

Syntax of atoi function:

The syntax for the function is given below:

int atoi(const char *pStr);

Convert the initial portion of the string pointed to by pStr to int representation.

 

Returns of atoi function:

The atoi function returns the converted value.

 

Note: The stdlib.h library must be included before using the atoi() function.

 

Example programs:

Let’s look at an example to understand the working of the atoi() function:

 

#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int iValue=0;
    char buff[]="1234";

    iValue=atoi(buff);//Convert numeric string to his integer value
    printf("%d\n",iValue);

    return 0;
}

Output: 1234

 

Important Points related to the atoi():

There are a few points that you should know before using the atoi().

1. Conversion stops when encountering the alphabetic character. See the below example,

#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int iValue=0;
    char buff[]="12a34";
    //Convert numeric string
    //to his integer value
    iValue=atoi(buff);

    printf("%d\n",iValue);

    return 0;
}

Output:  12

Explanation: In the above example, the input string is “12a34”. The conversion stops when encountering 'a' (alphabetic character). That is why the output is 12.

 

2. Discards any whitespace characters until the first non-whitespace character is found.

#include <stdio.h>
#include<stdlib.h>


int main()
{
    char* str1 = "  42";

    int num = atoi(str1);

    printf("%d",num);

    return 0;
}

Output:  42

 

3. If the string starts with a non-numeric character (except the whitespace characters), returns 0.

In the below example, an alphabetic character ‘a’ comes at the beginning of the string. We know that if alphabetic characters occur in between of the string then atoi()function immediately stops the conversion. So in this example atoi() return 0.

#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int iValue=0;
    char buff[]="a1234";

    //Convert numeric string
    //to his integer value
    iValue=atoi(buff);

    printf("%d\n",iValue);

    return 0;
}

Output: 0

 

4.If the converted value falls out of the range of the integer, the behavior is undefined. Consider the below example.

#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int iValue=0;
    char buff[]="100000000000";
    //Convert numeric string
    //to his integer value
    iValue=atoi(buff);

    printf("%d\n",iValue);

    return 0;
}

Output: Undefined

 

C program to implement own atoi() function:

Your compiler/standard library will likely have a very efficient and tailored implementation of the atoi() function. So if not required avoid creating your own version of the atoi function.

Let’s see some way to create our own atoi() function.

 

Method 1:

This implementation does not handle the negative number. So if you will pass the negative number it will return 0.

#include<stdio.h>

#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)

int StringToInt(const char *str)
{
    int num=0;
    while(Is_NUMERIC_STRING(str))
    {
        num=(num*10)+ (*str-48);
        str++;
    }

    return num;
}


int main()
{
    int d = StringToInt("1230");

    printf("%u\n",d);

    return 0;
}

Output: 1230

 

You can also write this code in another way.

#include<stdio.h>

#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)
#define CONVERSION(d,k)  ((d<<3) +(d<<1))+(*(char*)k-48);

int StringToInt(const char *str)
{
    int num = 0;
    while( Is_NUMERIC_STRING(str))
    {
        num = CONVERSION(num,str);
        str++;
    }
    return num;
}



int main()
{
    int d = StringToInt("1230");

    printf("%u\n",d);

    return 0;
}

 

Method-2:

The above methods do not handle the negative number and invalid pointer, so below another simple method that handles negative numbers and the invalid pointer.

#include<stdio.h>

#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)


int StringToInt(const char *pszBuffer)
{
    int result=0; // variable to store the result

    int sign = 1; //Initialize sign as positive

    if(pszBuffer == NULL) //If pointer is null
        return 0;

    //If number is negative, then update sign
    if((*pszBuffer) == '-')
    {
        sign = -1;

        ++pszBuffer; //Increment the pointer
    }

    while( Is_NUMERIC_STRING(pszBuffer)) //check string validity
    {

        result = (result*10)+ (*pszBuffer-48);

        pszBuffer++; //Increment the pointer
    }

    return (sign * result);
}



int main()
{
    int d;

    d = StringToInt("-1230");

    printf("%d\n",d);

    return 0;
}

 

OutPut: -1230

 

Method-3:

The second method handles the negative numbers but does not handle the leading whitespace. In the below method, I am handling the leading whitespace character. To discard all leading whitespace I simply run a loop until the whitespace character reaches the end.

#include<stdio.h>
#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)


int StringToInt(const char *pszBuffer)
{
    int result=0; // variable to store the result
    int sign = 1; //Initialize sign as positive

    if(pszBuffer == NULL) //If pointer is null
        return 0;

    // if whitespaces then ignore.
    while ((*pszBuffer) == ' ')
    {
        ++pszBuffer;
    }
    //If number is negative, then update sign
    if((*pszBuffer) == '-')
    {
        sign = -1;
        ++pszBuffer; //Increment the pointer
    }
    while( Is_NUMERIC_STRING(pszBuffer)) //check string validity
    {
        result = (result*10)+ (*pszBuffer-48);
        pszBuffer++; //Increment the pointer
    }
    return (sign * result);
}

int main()
{
    const int d = StringToInt(" -1230");

    printf("%d\n",d);

    return 0;
}

 

Recommended Articles for you: