#include <iostream>
#include <string>
int myAtoi(std::string str) {
int sign = 1, base = 0, i = 0;
// skip leading whitespaces
while (str[i] == ' ') {
i++;
}
// check for sign
if (str[i] == '-' || str[i] == '+') {
sign = (str[i++] == '-') ? -1 : 1;
}
// convert digits to integer
while (isdigit(str[i])) {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
int main() {
std::string str = "12345";
int result = myAtoi(str);
std::cout << "Converted integer: " << result << std::endl;
return 0;
}
這段代碼實現了一個簡單的atoi函數,可以將字符串轉換為整數。注意在實現時需要考慮一些邊界條件,比如正負號、溢出等情況。