C 庫 - atol() 函式



C 的stdlibatol() 函式用於將作為引數傳遞的字串轉換為長整型數字。例如,如果我們有字串“123”,並且我們想將其轉換為長整型 123,則可以使用 atol("123")。

此函式首先跳過任何前導空白字元,然後將後續字元作為數字的一部分進行處理。如果字串以“+”或“-”號開頭,則將其視為數字。當找到無效字串時,轉換停止。

語法

以下是 atol() 函式的 C 庫語法:

long int atol(const char *str)

引數

此函式接受單個引數:

  • str − 它是一個指向空終止字串的指標,表示一個長整型。

返回值

此函式返回一個長整型數字,表示長整型值。如果輸入字串不是有效的數字字串,則返回 0。

示例 1

以下是一個基本的 C 程式,它使用 atol() 函式將字串值轉換為長整型值。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   long int val;
   char *str; 
   str = "20152030";
   
   //convert string into long int
   val = atol(str); 
   printf("Long int value = %ld", val);
}

輸出

以下是輸出:

Long int value = 20152030

示例 2

讓我們來看另一個 C 程式,我們將兩個字串連線起來,然後使用 atol() 函式將結果字串轉換為長整型數字。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {	
   // Define two strings to concatenate
   char str1[] = "24";
   char str2[] = "2024";
   
   //calculate the length of string first + second
   int length = strlen(str1) + strlen(str2) + 1;

   // Allocate memory for the concatenated string
   char *concatenated = malloc(length);

   // check memory allocation if null return 1.
   if(concatenated == NULL) {
      printf("Memory allocation failed\n");
      return 1;
   }

   // Concatenate str1 and str2
   strcpy(concatenated, str1);
   strcat(concatenated, str2);

   // Convert concatenated string into a long int.
   // use the atol() function
   long int number = atol(concatenated);

   printf("The concatenated string is: %s\n", concatenated);
   printf("The long int value is: %ld\n", number);

   // at the last free the alocated memory
   free(concatenated);
   return 0;
}

輸出

以下是輸出:

The concatenated string is: 242024
The long int value is: 242024

示例 3

下面的 C 程式將字元字串轉換為長整型數字。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   long int res;
   char str[20];
   
   //define a string
   strcpy(str, "tutorialspointIndia");
   
   //use atoi() function
   res = atol(str);
   printf("String Value = %s\n", str);
   printf("Integral Number = %ld\n", res);
   
   return(0);
}

輸出

以下是輸出:

String Value = tutorialspointIndia
Integral Number = 0
廣告