如何在 C 語言中把字串轉換為整數

2025-11-19 20:38:37

atoi() 函式在 C 語言中把一個字串轉換為整數

strtol() 函式在 C 語言中把一個字串轉換為整數

strtoumax() 函式在 C 語言中將字串轉換為整數

本文介紹了 C 語言中把字串轉換成整數的不同方法。在 C 語言中,有幾種將字串轉換為整數的方法,如 atoi(),strtoumax() 和 strol()。

atoi() 函式在 C 語言中把一個字串轉換為整數

atoi() 函式在 C 語言程式設計中把字串轉換成整數。atoi() 函式忽略了字串開頭的所有空格,對空格後的字元進行轉換,然後在到達第一個非數字字元時停止。

atoi() 函式返回字串的整數表示。

我們需要包含 標頭檔案來使用 atoi() 函式。

atoi() 語法

int atoi(const char *str);

*str 是指向要轉換為整數的字串的指標。

atoi() 示例程式碼

#include

#include

#include

int main(void) {

int value;

char str[20];

strcpy(str, "123");

value = atoi(str);

printf("String value = %s, Int value = %d\n", str, value);

return (0);

}

輸出:

String value=123, Int value=123

strtol() 函式在 C 語言中把一個字串轉換為整數

strtol() 函式在 C 語言中把一個字串轉換成一個長整數。strtol() 函式省略了字串開頭的所有空格字元,在它把後面的字元轉換為數字的一部分之後,當它找到第一個不是數字的字元時就停止。

strtol() 函式返回字串的長整數值表示。

我們需要包含 標頭檔案來使用 atoi() 函式。

strtol() 語法

long int strtol(const char *string, char **laststr, int basenumber);

*string 是指向要轉換為長整數的字串的指標。

**laststr 是一個指示轉換停止位置的指標。

basenumber 是基數,範圍為 [2, 36]。

#include

#include

#include

int main(void) {

char str[10];

char *ptr;

long value;

strcpy(str, " 123");

value = strtol(str, &ptr, 10);

printf("decimal %ld\n", value);

return 0;

}

輸出:

decimal 123

strtoumax() 函式在 C 語言中將字串轉換為整數

strtoumax() 函式將一個字串的內容解釋為指定基數的整數形式。它省略任何空格字元,直到第一個非空格字元。然後,它儘可能多的字元形成一個有效的基數整數表示,並將它們轉換為一個整數值。

strtoumax() 返回一個字串的相應整數值。如果轉換沒有成功,該函式返回 0。

strtoumax() 語法

uintmax_t strtoumax(const char* string, char** last, int basenumber);

*string 是指向要轉換為長整數的字串的指標。

**last 是一個指示轉換停止位置的指標。

basenumber 是基數,範圍是 [2, 36]。

strtoumax() 示例

#include

#include

#include

int main(void) {

char str[10];

char *ptr;

int value;

strcpy(str, " 123");

printf("The integer value:%d", strtoumax(str, &ptr, 10));

return 0;

}

輸出:

The long integer value: 123

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

#提供获取用户信息接口
第九节 古代体表部位名称解释