C++ Studio (二) ----- atoi()函數的實現 (自己編寫功能)


上一篇博客講的是atoi()函數的功能及舉例,現在呢,就自己寫寫代碼(根據atoi()的功能)來表示atoi()函數的實現。我在這里先把atoi()函數的功能貼出來,也好有個參考啊~~~

    atoi()函數的功能:將字符串轉換成整型數;atoi()會掃描參數nptr字符串,跳過前面的空格字符,直到遇上數字或正負號才開始做轉換,而再遇到非數字或字符串時('\0')才結束轉化,並將結果返回(返回轉換后的整型數)。

    atoi()函數實現的代碼:

  

 1 /* 
 2 * name:xif 
 3 * coder:xifan@2010@yahoo.cn 
 4 * time:08.20.2012 
 5 * file_name:my_atoi.c 
 6 * function:int my_atoi(char* pstr) 
 7 */  
 8   
 9 int my_atoi(char* pstr)  
10 {  
11     int Ret_Integer = 0;  
12     int Integer_sign = 1;  
13       
14     /* 
15     * 判斷指針是否為空 
16     */  
17     if(pstr == NULL)  
18     {  
19         printf("Pointer is NULL\n");  
20         return 0;  
21     }  
22       
23     /* 
24     * 跳過前面的空格字符 
25     */  
26     while(isspace(*pstr) == 0)  
27     {  
28         pstr++;  
29     }  
30       
31     /* 
32     * 判斷正負號 
33     * 如果是正號,指針指向下一個字符 
34     * 如果是符號,把符號標記為Integer_sign置-1,然后再把指針指向下一個字符 
35     */  
36     if(*pstr == '-')  
37     {  
38         Integer_sign = -1;  
39     }  
40     if(*pstr == '-' || *pstr == '+')  
41     {  
42         pstr++;  
43     }  
44       
45     /* 
46     * 把數字字符串逐個轉換成整數,並把最后轉換好的整數賦給Ret_Integer 
47     */  
48     while(*pstr >= '0' && *pstr <= '9')  
49     {  
50         Ret_Integer = Ret_Integer * 10 + *pstr - '0';  
51         pstr++;  
52     }  
53     Ret_Integer = Integer_sign * Ret_Integer;  
54       
55     return Ret_Integer;  
56 }  

 

  

 

    現在貼出運行my_atoi()的結果,定義的主函數為:int  main  ()

  

   

 1 int main()  
 2 {  
 3     char a[] = "-100";  
 4     char b[] = "456";  
 5     int c = 0;  
 6       
 7     int my_atoi(char*);   
 8   
 9     c = atoi(a) + atoi(b);  
10       
11     printf("atoi(a)=%d\n",atoi(a));  
12     printf("atoi(b)=%d\n",atoi(b));  
13     printf("c = %d\n",c);  
14   
15     return 0;  
16 }  

 

 


    運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM