模拟实现atoi函数c语言
时间: 2023-05-27 11:06:36 浏览: 118
用C实现atoi函数
4星 · 用户满意度95%
```c
#include <stdio.h>
int atoi(char *s) {
int i = 0, sign = 1, result = 0;
char c;
// skip white space
while (s[i] == ' ') {
i++;
}
// handle sign
if (s[i] == '+' || s[i] == '-') {
sign = (s[i++] == '+') ? 1 : -1;
}
// convert digits
while (s[i] >= '0' && s[i] <= '9') {
result = result * 10 + (s[i++] - '0');
}
return sign * result;
}
int main() {
char s1[] = "123";
char s2[] = "-456";
char s3[] = " 789";
char s4[] = "+0123";
printf("%d\n", atoi(s1)); // expect 123
printf("%d\n", atoi(s2)); // expect -456
printf("%d\n", atoi(s3)); // expect 789
printf("%d\n", atoi(s4)); // expect 123
return 0;
}
```
阅读全文