atol(atoi)函數的實現要點

來源:互聯網
上載者:User

以下是c標準庫中該函數的實現代碼,從中分析要點

  1. /*** 
  2. *atox.c - atoi and atol conversion 
  3. * 
  4. * Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved. 
  5. * 
  6. *Purpose: 
  7. * Converts a character string into an int or long. 
  8. * 
  9. *******************************************************************************/  
  10.   
  11. /*** 
  12. *long atol(char *nptr) - Convert string to long 
  13. * 
  14. *Purpose: 
  15. * Converts ASCII string pointed to by nptr to binary. 
  16. * Overflow is not detected. 
  17. * 
  18. *Entry: 
  19. * nptr = ptr to string to convert 
  20. * 
  21. *Exit: 
  22. * return long int value of the string 
  23. * 
  24. *Exceptions: 
  25. * None - overflow is not detected. 
  26. * 
  27. *******************************************************************************/  
  28.   
  29. long __cdecl atol(  
  30.                   const char *nptr  
  31.                   )  //1.const修飾
  32. {  
  33.     int c;          /* current char */  
  34.     long total;     /* current total */  
  35.     int sign;       /* if ''-'', then negative, otherwise positive */  
  36.   
  37.     /* skip whitespace */ 

  38. //char ,signed char 、unsigned char 類型的資料具有相同的特性然而當你把一個單位元組的數賦給一個整型數時,便會看到它們在符號擴充上的差異。
  39. //ascii碼當賦給整形數時要轉為unsigned char再轉為int
  40.     while ( isspace((int)(unsigned char)*nptr) )  //2.去掉首部的空格
  41.         ++nptr;  
  42.   
  43.     c = (int)(unsigned char)*nptr++;  //取得第一個非空格的字元
  44.     sign = c; /* save sign indication */  
  45.     if (c == '-' || c == '+')  //如果第一個非空白字元為符號
  46.         c = (int)(unsigned char)*nptr++; /* skip sign */  //跳過符號,將符號後的那個字元給c
  47.   
  48.     total = 0;  //結果置為0
  49.   
  50.     while (isdigit(c)) {  //3.如果碰到非法字元則停止
  51.         total = 10 * total + (c - '0'); /* accumulate digit */  
  52.         c = (int)(unsigned char)*nptr++; /* get next char */  
  53.     }  
  54.   
  55.     if (sign == '-')  
  56.         return -total;  
  57.     else  
  58.         return total; /* return result, negated if necessary */  
  59. } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.