要自定義一個類似atoi的函數,可以按照以下步驟編寫代碼:
下面是一個簡單的示例代碼:
#include <iostream>
#include <cstring>
int myAtoi(const char* str) {
int result = 0;
int sign = 1;
int i = 0;
// 處理空格
while (str[i] == ' ') {
i++;
}
// 處理正負號
if (str[i] == '-' || str[i] == '+') {
sign = (str[i++] == '-') ? -1 : 1;
}
// 轉換數字字符為整數值
while (str[i] >= '0' && str[i] <= '9') {
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i] - '0' > INT_MAX % 10)) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
result = result * 10 + (str[i++] - '0');
}
return result * sign;
}
int main() {
const char* str = "123";
int num = myAtoi(str);
std::cout << num << std::endl;
return 0;
}
在這個示例中,函數myAtoi實現了類似atoi的功能,可以將一個字符串轉換為整數值。在主函數中,我們將字符串"123"傳遞給myAtoi函數,并打印出轉換后的整數值。