Thursday, 5 November 2015

Write your own atoi()

The atoi() function takes a string (which represents an integer) as an argument and returns its value.
Following is a simple implementation. We initialize result as 0. We start from the first character and update result for every character.
// A simple C++ program for implementation of atoi
#include <stdio.h>
 
// A simple atoi() function
int myAtoi(char *str)
{
    int res = 0; // Initialize result
 
    // Iterate through all characters of input string and update result
    for (int i = 0; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';
 
    // return result.
    return res;
}
 
// Driver program to test above function
int main()
{
    char str[] = "89789";
    int val = myAtoi(str);
    printf ("%d ", val);
    return 0;
}
Output:
89789
The above function doesn’t handle negative numbers. Following is a simple extension to handle negative numbers.
// A C++ program for implementation of atoi
#include <stdio.h>
 
// A simple atoi() function
int myAtoi(char *str)
{
    int res = 0;  // Initialize result
    int sign = 1;  // Initialize sign as positive
    int i = 0;  // Initialize index of first digit
     
    // If number is negative, then update sign
    if (str[0] == '-')
    {
        sign = -1; 
        i++;  // Also update index of first digit
    }
     
    // Iterate through all digits and update the result
    for (; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';
   
    // Return result with sign
    return sign*res;
}
 
// Driver program to test above function
int main()
{
    char str[] = "-123";
    int val = myAtoi(str);
    printf ("%d ", val);
    return 0;
}
Output:
-123
The above implementation doesn’t handle errors. What if str is NULL or str contains non-numeric characters.Following implementation handles errors.
// A simple C++ program for implementation of atoi
 
#include <stdio.h>
 
// A utility function to check whether x is numeric
bool isNumericChar(char x)
{
    return (x >= '0' && x <= '9')? true: false;
}
 
// A simple atoi() function. If the given string contains
// any invalid character, then this function returns 0
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 number is negative, then update sign
    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] != '\0'; ++i)
    {
        if (isNumericChar(str[i]) == false)
            return 0; // You may add some lines to write error message
                      // to error stream
        res = res*10 + str[i] - '0';
    }
 
    // Return result with sign
    return sign*res;
}
 
// Driver program to test above function
int main()
{
    char str[] = "-134";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}
Time Complexity: O(n) where n is the number of characters in input string.
Exercise
Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

No comments:

Post a Comment