c++ myatoi
时间: 2024-01-24 20:15:15 浏览: 60
以下是一个C++实现的myAtoi函数的例子:
```cpp
#include <iostream>
#include <climits>
int myAtoi(std::string s) {
int sign = 1;
int i = 0;
int result = 0;
// 跳过空格
while (s[i] == ' ') {
i++;
}
// 处理正负号
if (s[i] == '-' || s[i] == '+') {
sign = (s[i++] == '-') ? -1 : 1;
}
// 转换数字
while (i < s.length() && isdigit(s[i])) {
int digit = s[i] - '0';
// 处理溢出情况
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > INT_MAX % 10)) {
return (sign == -1) ? INT_MIN : INT_MAX;
}
result = result * 10 + digit;
i++;
}
return result * sign;
}
int main() {
std::string s = "-42";
int result = myAtoi(s);
std::cout << "Converted number: " << result << std::endl;
return 0;
}
```
阅读全文