- 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 庫 - atoi() 函式
C 的stdlib 庫 atoi() 函式用於將數字字串轉換為整數值。
整數是一個可以是正數或負數(包括零)的整數。它不能是分數、小數或百分比,例如,1、2、-5 和 -10 等數字是整數。
語法
以下是 c atoi() 函式的語法 -
int atoi(const char *str)
引數
此函式接受一個引數 -
-
str - 它是指向空終止字串的指標,表示一個整數。
返回值
此函式返回一個整數,表示 int 值。如果輸入字串不是有效的字串數字,則返回 0。
示例 1
以下是使用 atoi() 將字串值轉換為整數值的基本 c 示例。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int val;
char *str;
str = "1509.10E";
val = atoi(str);
printf("integral number = %d", val);
}
輸出
以下是輸出 -
integral number = 1509
示例 2
下面的 c 示例連線兩個字串,然後使用 atoi() 將結果字串轉換為整數。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Define two strings to concatenate
char str1[] = "2023";
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 integral number.
// use the atoi() function
int number = atoi(concatenated);
printf("The concatenated string is: %s\n", concatenated);
printf("The integral number is: %d\n", number);
// at the last free the alocated memory
free(concatenated);
return 0;
}
輸出
以下是輸出 -
The concatenated string is: 20232024 The integral number is: 20232024
示例 3
以下是 atoi() 的另一個示例,這裡我們將字元字串轉換為整數。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int res;
char str[25];
//define a string
strcpy(str, "tutorialspoint India");
//use atoi() function
res = atoi(str);
printf("String Value = %s\n", str);
printf("Integral Number = %d\n", res);
return(0);
}
輸出
以下是輸出 -
String Value = tutorialspoint India Integral Number = 0
廣告