Atoi function in c

ATOI FUNCTION

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

int main ()
{
    int i;
    char buffer [256];

     printf ("Enter a number: ");
     fgets (buffer, 256, stdin);

     i = atoi (buffer);
     printf ("The value entered is %d.",i);
     return 0;
}

OWN ATOI FUNCTION

#include <stdio.h>
 
// A utility function to check whether x is numeric
bool isNumericChar(char x)
{
    return (x >= '0' && x <= '9')? true: false;
}
 
int myAtoi(char *str)
{
    if (*str == NULL)
       return 0;
    int res = 0;  // Initialize result
    int sign = 1;  // Initialize sign as positive
    int i = 0;  // Initialize index of first digit
 
    if (str[0] == '-')
    {
        sign = -1;
        i++;  // Also update index of first digit
    }
 
    // Iterate through all digits of input string and update result
    for (; str[i] != ''; ++i)
    {
        if (isNumericChar(str[i]) == false)
            return 0;
        res = res*10 + str[i] - '0';
    }

    return sign*res;
}
 
// Driver program to test above function
int main()
{
    char str[] = "-134";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}
This entry was posted in C. Bookmark the permalink.

Leave a comment