在C語言中,可以使用庫函數(shù)atoi
或strtol
來實現(xiàn)字符串轉換為數(shù)字的功能。
atoi
函數(shù):#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("The number is: %d\n", num);
return 0;
}
strtol
函數(shù):#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
char *endptr;
long num = strtol(str, &endptr, 10);
if (*endptr != '\0') {
printf("Invalid number\n");
} else {
printf("The number is: %ld\n", num);
}
return 0;
}
這兩種方法都可以將字符串轉換為對應的整數(shù),但是strtol
函數(shù)更加靈活,可以處理更多的異常情況,比如字符串中包含非數(shù)字字符。