atoi C++实现
时间: 2023-08-27 14:20:14 浏览: 177
下面是一个C语言中实现atoi函数的例子:
```C
#include <stdio.h>
int myAtoi(char* str) {
int i = 0;
int sign = 1;
long ret = 0;
// 跳过空格
while (str[i == ' ' && str[i != '\0') {
i++;
}
// 处理符号
if (str[i == '-') {
sign = -1;
i++;
} else if (str[i == '+') {
sign = 1;
i++;
}
// 计算数字
while (str[i >= '0' && str[i <= '9') {
ret = ret * 10 + (str[i - '0');
// 检查溢出
if (ret * sign < INT_MIN) {
return INT_MIN;
} else if (ret * sign > INT_MAX) {
return INT_MAX;
}
i++;
}
return (int)(ret * sign);
}
int main() {
char str[] = "123";
int result = myAtoi(str);
printf("%d\n", result);
return 0;
}
```
这个函数实现了将一个字符串转换为整数的功能。它会跳过字符串前面的空格,并处理正负号。然后,它会逐个处理字符串中的字符,将其转换为数字。如果遇到非数字字符,则停止转换。如果转换后的结果超出了INT_MIN和INT_MAX的范围,则返回相应的边界值。最后,返回转换后的整数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [实现atoi函数(C++实现)](https://blog.csdn.net/zrh_CSDN/article/details/80006177)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [C++实现atoi](https://blog.csdn.net/centor/article/details/104119061)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [自己实现的atoi函数](https://download.csdn.net/download/welove20101/4177714)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文