C++代码:
#include<iostream>
#include<cmath>
using namespace std;
int atoi(const char *str) {
if (str == NULL) {
return 0;
}
int n = strlen(str), i = 0;
bool flag = true;
long long res = 0;
while (str[i] == ' ' || str[i] == '0') {
i++;
}
if (str[i] == '+') {
flag = true;
i++;
}
else if (str[i] == '-') {
flag = false;
i++;
}
for (; i<n; i++) {
if (str[i] >= '0'&&str[i] <= '9') {
res = res * 10 + (str[i] - '0');
}
else {
break;
}
}
if (!flag)
res = -1 * res;
if (res>INT_MAX)
return INT_MAX;
else if (res<INT_MIN)
return INT_MIN;
else return res;
}
int main() {
int num,res;
char str[200];
cout << "Please input the number of string:";
cin >> num;
cout << "Please input the string:";
for (int i = 0; i < num; i++) {
cin >> str[i];
}
res = atoi(str);
cout << "The result:" << res << endl;
return 0;
}
C++运行结果: