
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - strtoul() 函式
C 的stdlib 庫 strtoul() 函式根據給定的基數將字串的初始部分轉換為無符號長整型數字,該基數必須在 2 到 32(包括 2 和 32)之間,或者為特殊值 0。
當整數的大小超出普通整數型別的範圍時,使用 strtoul() 函式。它也用於轉換表示不同基數的數字的字串,例如將二進位制轉換為十六進位制。
語法
以下是 strtoul() 函式的 C 庫語法:
unsigned long int strtoul(const char *str, char **endptr, int base)
引數
此函式接受以下引數:
-
str - 要轉換為無符號長整型值的字串。
-
endptr - char* 型別的物件的引用,函式將其值設定為 str 中數值後的下一個字元。
-
base - 表示數字系統的基數(例如,10 表示十進位制,16 表示十六進位制,或 0 表示特殊情況)。
返回值
此函式返回轉換後的無符號長整型值。如果輸入字串無效,則返回 0。
示例 1
在此示例中,我們建立一個基本的 C 程式來演示如何使用 strtoul() 函式。
#include <stdio.h> #include <stdlib.h> int main() { const char *str = "12532abc"; char *endptr; unsigned long int value; //use the strtoul() function value = strtoul(str, &endptr, 0); printf("The unsigned long integer is: %lu\n", value); printf("String part is: %s", endptr); return 0; }
輸出
以下是輸出:
The unsigned long integer is: 12532 String part is: abc
示例 2
以下示例使用 strtoul() 函式將字串的數字部分轉換為無符號長十六進位制整數。
#include <stdio.h> #include <stdlib.h> int main() { // initializing the string char str[150] = "202405Tutorialspoint India"; // reference pointer char* endptr; unsigned long int value; // finding the unsigned long // integer with base 16 value = strtoul(str, &endptr, 16); // displaying the unsigned number printf("The unsigned long integer is: %lu\n", value); printf("String in str is: %s", endptr); return 0; }
輸出
以下是輸出:
The unsigned long integer is: 2106373 String in str is: Tutorialspoint India
示例 3
讓我們再建立一個示例,我們嘗試將不包含任何數字字元的字串轉換為無符號長十進位制數字。
#include <stdio.h> #include <stdlib.h> int main() { const char *str = "abcde"; char *endptr; unsigned long int value; //use the strtoul() funcion value = strtoul(str, &endptr, 10); if (value == 0 && endptr == str) { printf("No numeric characters were found in the string.\n"); } printf("unsigned long integer is: %lu\n", value); printf("String part is: %s", endptr); return 0; }
輸出
以下是輸出:
No numeric characters were found in the string. unsigned long integer is: 0 String part is: abcde
廣告