函数atoi(),将字符串转换为整型数值。库函数atio的原型如下:
int atoi(const char* p),下面是实现,如有不足之处,还望指正!
// myAtoi.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <math.h> using namespace std; int myAtoi(const char* str) { int num = 0; bool isNegative = false; int n = 0; const char* p = str; if (p == NULL) { return -1; } while (*p++ != '\0') { n++; } p = str; if (p[0] == '-') { isNegative = true; } char temp = '0'; for (int i = 0; i < n; i++) { char temp = *p++; if (temp > '9' || temp < '0') { continue; } if (num != 0 || temp != '0') { temp -= 0x30; num += temp * static_cast<int>(pow(10.0, n-1-i)); } } if (isNegative) { return (0-num); } else { return num; } } int _tmain(int argc, _TCHAR* argv[]) { char* str = "-1230045"; int num = 0; num = myAtoi(str); cout << num << endl; return 0; }