/* Implementation of * int atoi(char *) * Print negative sign if there is one. * If the return number is bigger than * 2^31-1, return 2^31-1. */ #includeusing namespace std; int atoi(char *ptr) { int i = 0; int flag = 1; int result = 0; // determine the first non white-space char while( ptr[i] == ' ') i++; if( ptr[i] == '+') {flag = 1; i++;} if( ptr[i] == '-') {flag = -1; i++;} // if the first non-space char is not a number, // return 0 if ( ptr[i] < 48 || ptr[i] > 57 ) return 0; // if the first non-space char is a number... result =static_cast ( ptr[i]) - 48; i++; while(ptr[i] >=48 && ptr[i] <=57 ) { result = result*10 + (static_cast (ptr[i]) - 48); if (result < 0) return 2147483647; i++; } return flag*result; } int main() { char a[10] = " 123a4"; char b[20] = " abc321 44"; char c[20] = " 3 44 5"; char d[20] = " 2147483648 "; char e[30] = " -345 "; char f[30] =" +345 "; char g[30] = " --345 "; cout << atoi(a) << endl; cout << atoi(b) << endl; cout << atoi(c) << endl; cout << atoi(d) << endl; cout << atoi(e) << endl; cout << atoi(f) << endl; cout << atoi(g) << endl; return 0; }
[C++] An implementation of atoi
Posted at
7/05/2011 06:07:00 PM
This is an implementation of atoi function I wrote. Seems it works.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment