Function atoi | An implementation

According to C++ Reference the function atoi is described as follows:
int atoi(const char* str);
  • The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. 
  • The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
  • If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned. 

The following is an attempt to implement the function in C.
int stringToInt(const char* input) { // C implementation
    int ans = 0;
    int sign = 1;

    if (!input) {
        return ans;
    }

    //Check for sign at the beginning
    if ( (*input == '-' && (sign = -1) ) || (*input == '+') ) {
        input++;
    }

    while (*input) {
        //If the character is a digit, use it
        if (*input >= '0' && *input <= '9') {
            ans = ans * 10 + (*input - '0') ;
        } else { // Return once a non-digit charcter is encountered
            return ans * sign;
        }
        input++;
    }
    return ans * sign;
}
A simpler implementation (though costlier) can be done in C++.
int stringToInt(std::string& input) { //C++ implementation
    int ans = 0;

    if (!input) {
        return ans;
    }

    //store the string as an input string stream
    std::istringstream iss(input);

    //if the conversion fails or does not reach eof, the conversion is not a success
    if ( (iss >> std::ws >> ans).fail() || !(iss >> std::ws).eof() ) {
        //Throwing a custom exception
        StringToIntException e("Illegal characters in string input");
        throw e;
    } else {
        return ans;
    }
}

No comments:

Post a Comment