C 语言实现 atoi()
约 363 字
预计阅读 1 分钟
手写一个 atoi() 函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#include <stdio.h>
#include <limits.h>
// 返回值
// 0 : 成功
// -1 : 错误,异常输入
// -2 : 结果溢出(超出 int 能表示的最大范围)
int atoi(const char* in, int *out){
int sign = 1;
int res = 0;
int i = 0;
if (in[0] == '-') {
sign = -1;
i++;
}
for (; in[i] != '\0'; ++i) {
if ( !(in[i] >= '0' && in[i] <= '9') ){
// 检查完输入字符串符号后,
// 如果扫描到非数字直接返回错误码
// 不改变 out 值
return -1; // 返回错误码-1
}
// int 范围 -2147483648 2147483647
if (res > INT_MAX / 10 // 处理边界条件
|| res == INT_MAX / 10 && sign == -1 && in[i] > '8'
|| res == INT_MAX / 10 && sign == 1 && in[i] > '7'
) {
// 结果溢出
return -2;
}
res = res * 10 + in[i] - '0';
}
// 把正确结果写入 out,返回 0 表示转换成功
*out = sign * res;
return 0;
}
int main() {
char str[] = "-2147483649";
int res = 0;
int val = atoi(str, &res);
printf("res code:%d, value: %d\n", val, res);
return 0;
}
|
手动测试结果如下
1
2
3
4
5
6
7
8
9
10
11
12
|
root@VM-20-16-ubuntu:~/del# gcc atoi.c
root@VM-20-16-ubuntu:~/del# ./a.out
res code:-1, value: 0
root@VM-20-16-ubuntu:~/del# gcc atoi.c
root@VM-20-16-ubuntu:~/del# ./a.out
res code:0, value: -12222334
root@VM-20-16-ubuntu:~/del# gcc atoi.c
root@VM-20-16-ubuntu:~/del# ./a.out
res code:0, value: 2147483647
root@VM-20-16-ubuntu:~/del# gcc atoi.c
root@VM-20-16-ubuntu:~/del# ./a.out
res code:0, value: -2147483647
|