文章目錄
- 1 atoi()函數
- 1.1 函數原型
- 1.2 參數
- 1.3 返回值
- 1.4 轉換機制
- 1.5 示例
- 1.5.1 示例1
1 atoi()函數
1.1 函數原型
atoi():將str指向的字符串轉換為整數,函數原型如下:
int atoi(const char *str);
1.2 參數
atoi()函數只有一個參數str:
- 參數str是指向要轉換為整數的字符串的指針,類型為char*型。
1.3 返回值
atoi()函數的返回值類型為int型。
- 轉換成功,返回轉換后的int型整數;
- 轉換失敗,返回0值。
1.4 轉換機制
- atoi()函數將str指向的字符串轉換為int型整數;
- atoi()函數將字符串轉換為整數的過程類似于scanf()函數從stdin中讀取字符賦值給變量的過程:
(1)有效字符為±符號和數字字符1-9;
(2)跳過所有空字符;
(3)如果第一非空字符是無效字符,則轉換失敗,返回0值;
(4)如果第一非空字符是有效字符,則轉換繼續,直至遇到第一個無效字符為止(無效字符包括字母、標點符號和空字符等)。
C語言標準描述如下:
1. Interprets an integer value in a byte string pointed to by str.
2. The implied radix is always 10.
3. Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value.
4. The valid integer value consists of the following parts:--- (optional) plus or minus sign--- numeric digits
5. If the value of the result cannot be represented, i.e. the converted value falls out of range of the corresponding return type, the behavior is undefined.
1.5 示例
1.5.1 示例1
代碼如下在這里插入代碼片
所示:
int main()
{printf("%d\n", atoi("123"));printf("%d\n", atoi("123a"));printf("%d\n", atoi("a123"));printf("%d\n", atoi(" 123"));printf("%d\n", atoi("1 23"));printf("%d\n", atoi("+123"));printf("%d\n", atoi("-123"));printf("%d\n", atoi("1.23"));printf("%d\n", atoi("2147483648"));return 0;
}
代碼運行結果如下圖所示: