atoi的实现

atoi的实现

需要注意:

1.正负数

2.字符串是否有效

3.字符串是否溢出(此处省略)

 1 /*************************************************************************
 2     > File Name: my_atoi.c
 3     > Author: ChenPeng
 4     > Mail:479103815@qq.com 
 5     > Blog: http://www.cnblogs.com/cpsmile/
 6     > Created Time: Fri 03 Apr 2015 06:34:34 PM CST
 7  ************************************************************************/
 8 #include<stdio.h>
 9 #include<stdlib.h>
10 
11 /* 将字符串转数字换为对应的整数*/
12 int  my_atoi(char *str)
13 {
14     int isPos = 1; //记录是否是正数,1表示正数,否则是负数
15     int sum = 0;
16     if(*str == '-')
17     {
18         isPos = 0;//为负数
19         ++str;
20     }
21     while(*str != '')
22     {
23         if(*str < '0' || *str > '9')
24             break;
25         else
26         {
27             sum = sum * 10 + (*str) - '0';
28             ++str;
29         }
30     }
31     if(*str != '')
32     {
33         printf("The string is invalid!
");
34         return 0;
35     }
36     else
37         return isPos > 0 ? sum : -sum;
38 }
39 
40 int main()
41 {
42     char str[30] = "";
43     int val;
44     while(printf("Please enter a string:
"),scanf("%s",str) == 1)
45     {
46         val = my_atoi(str);
47         printf("整数为:%d
",val);
48     }
49     return 0;
50 }
原文地址:https://www.cnblogs.com/cpsmile/p/4390856.html