text: Write your own atoi ( ) | A simple C ++ program for implementation of atoi ; if whitespaces then ignore . ; sign of number ; checking for valid input ; handling overflow test case ; Driver Code ; Functional Code
code: #include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE int myAtoi ( const char * str ) { int sign = 1 , base = 0 , i = 0 ; while ( str [ i ] == ' ▁ ' ) { i ++ ; } if ( str [ i ] == ' - ' str [ i ] == ' + ' ) { sign = 1 - 2 * ( str [ i ++ ] == ' - ' ) ; } while ( str [ i ] >= '0' && str [ i ] <= '9' ) { if ( base > INT_MAX / 10 || ( base == INT_MAX / 10 && str [ i ] - '0' > 7 ) ) { if ( sign == 1 ) return INT_MAX ; else return INT_MIN ; } base = 10 * base + ( str [ i ++ ] - '0' ) ; } return base * sign ; } int main ( ) { char str [ ] = " ▁ - 123" ; int val = myAtoi ( str ) ; printf ( " % d ▁ " , val ) ; return 0 ; }