C庫 - strtol() 函式



C 的stdlibstrtol() 函式用於根據給定的基數將字串轉換為長整型數字。基數必須在 2 到 32(包括 2 和 32)之間,或者為特殊值 0。

語法

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

long int strtol(const char *str, char **endptr, int base)

引數

此函式接受以下引數:

  • str − 要轉換為長整型值的字串。

  • endptr − 指向字元指標的指標,用於儲存數值後第一個字元的指標。

  • base − 表示數字系統的基數(例如,10 表示十進位制,16 表示十六進位制)。

返回值

此函式返回轉換後的長整型值。如果輸入字串無效,則返回 0。

示例 1

在這個例子中,我們建立了一個基本的C程式來演示如何使用strtol()函式。

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

int main() {
   const char *str = "12345abc";
   char *endptr;
   long int num;

   // Convert the string to a long integer
   num = strtol(str, &endptr, 10);
   if (endptr == str) {
      printf("No digits were found.\n");
   } else if (*endptr != '\0') {
      printf("Invalid character: %c\n", *endptr);
   } else {
      printf("The number is: %ld\n", num);
   }
   return 0;
}

輸出

以下是輸出:

Invalid character: a

示例 2

下面的示例使用 strtol() 函式將十進位制數字字串轉換為長十進位制整數。

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

int main() {
   const char *str = "12205";
   char *endptr;
   long int num;

   // Convert the string to a long integer
   num = strtol(str, &endptr, 10);
   
   //display the long integer number    
   printf("The number is: %ld\n", num);    
   return 0;
}

輸出

以下是輸出:

The number is: 12205

示例 3

讓我們再建立一個示例,使用 strtol() 函式將數字轉換為長十六進位制數。

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

int main() {
   const char *str = "2024 tutorialspoint";
   char *endptr;
   long int num;
   
   // Convert the string to a long integer
   num = strtol(str, &endptr, 16);
   
   //display the long hexadecimal integer number    
   printf("The hexadecimal number is: %ld\n", num);
   return 0;
}

輸出

以下是輸出:

The hexadecimal number is: 8228
廣告
© . All rights reserved.