函式
<cstdlib>

atol

long int atol ( const char * str );
將字串轉換為長整數
該函式解析C風格字串str,將其內容解釋為整數,並返回long int型別的值。

該函式首先儘可能多地跳過空白字元(如isspace中的定義),直到找到第一個非空白字元。然後,從該字元開始,讀取可選的初始加號減號,後跟儘可能多的十進位制數字,並將它們解釋為數值。

字串中可能包含構成整數數字之後的其他字元,這些字元將被忽略,對該函式行為沒有影響。

如果str中的第一個非空白字元序列不是有效的整數,或者由於str為空或僅包含空白字元而不存在這樣的序列,則不執行轉換,返回零。

引數

str
包含整數表示的 C 字串。

返回值

成功時,該函式將轉換後的整數作為long int值返回。
如果無法執行有效的轉換,則返回零值。
如果轉換後的值超出long int可表示的範圍,則會導致未定義行為。如果可能出現這種情況,請參閱strtol以獲得更健壯的跨平臺替代方法。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* atol example */
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atol */

int main ()
{
  long int li;
  char buffer[256];
  printf ("Enter a long number: ");
  fgets (buffer, 256, stdin);
  li = atol(buffer);
  printf ("The value entered is %ld. Its double is %ld.\n",li,li*2);
  return 0;
}

輸出

Enter a number: 567283
The value entered is 567283. Its double is 1134566.


資料競爭

訪問由 str 指向的陣列。

異常 (C++)

無異常保證:此函式從不丟擲異常。

如果str不指向有效的C風格字串,或者轉換後的值超出long int可表示的範圍,則會導致未定義行為

另見