Understanding atoi () function

atoi function

  Function: integer into a string

 1 #include <iostream>
 2 
 3 using namespace std;
 4 int atoi_my(const char *str)
 5 {
 6     int s = 0;
 7     bool flag = false;
 8     while(*str == ' ')
 9     {
10         str++;
11     }
12     if(*str == '-' || *str == '+')
13     {
14         if(*str == '-')
15         {
16             flag = true;
17             str++;
18         }
19         
20     }
21     while(*str >= '0' && *str <='9')
22     {
23         s = s*10 + *str -'0';
24         str++;
25         if(s<0)
26         {
27             s=2147483647;
28             break;
29         }
30     }
31     return s*(flag?-1:1);    
32 }
33 
34 int main()
35 {
36     char data[5] = "460";
37     int s ;
38     s = atoi_my(data);
39     cout <<s<<endl;
40     return 0 ;
41 }

 

Guess you like

Origin www.cnblogs.com/Yu-Weijie/p/11789012.html