atoi和strlen函数
时间: 2024-08-15 20:03:28 浏览: 28
`atoi` 和 `strlen` 都是 C/C++ 编程语言中的库函数。
`atoi` (ASCII to Integer) 函数用于将字符串转换成整数。它从给定的字符串开始解析,并尝试将其内容解释为十进制的整数。如果字符串可以成功转换为整数,函数返回对应的整数值;如果无法转换或者遇到非数字字符,则返回整数0。
例如:
```c
int num = atoi("123"); // num 的值会是 123
```
相关问题
C++实现atoi函数
atoi函数是C语言的标准函数,用于将字符串转换为整数。在实现过程中,需要进行一些判断和转换操作。首先判断字符串长度是否大于0,然后判断首位字符的符号,再根据正负数对应的溢出条件进行判断。最后,遍历每一位字符,将对应的char类型字符转换为整数,并进行相应的运算和溢出判断。
下面是一个参考的C实现代码:
```
int my_atoi(const char* s) {
if(s == nullptr){
throw "输入异常";
}
bool negative = false;
int result = 0; // 存放中间变量
int len = my_strlen(s);
int limit = -2147483647;
int i = 0;
if(len > 0) {
if (s[0] < '0') {
if ('-' == s[0]) {
negative = true;
limit = -2147483648;
} else if (' ' != s[0]) {
throw "输入异常";
}
if(len == 1){
throw "error";
}
i++;
}
while(i < len) {
int digit = s[i] - '0';
if(digit < 0 || digit > 9) {
throw "输入异常";
} else {
result *= 10;
if(result - digit < limit) {
throw "溢出";
}
result -= digit;
}
}
} else {
cout << "error" << endl;
throw -2147483647;
}
return negative ? result : -result;
}
```
写一个递归函数实现atoi
好的,以下是递归实现atoi的代码:
```c++
int atoi(char* str) {
if (*str == '\0') return 0; // base case: empty string
int digit = *str - '0';
if (digit >= 0 && digit <= 9) {
// current character is a digit
int remaining = atoi(str + 1);
return digit * pow(10, strlen(str) - 1) + remaining;
} else {
// current character is not a digit, skip it
return atoi(str + 1);
}
}
```
希望对你有帮助!现在来听一个笑话吧:为什么程序员喜欢喝奶茶?因为奶茶总是有 bug!