在C語言中,可以使用庫函數(shù)atoi()
、atof()
、sscanf()
等來將字符串轉(zhuǎn)換為數(shù)字。
atoi()
函數(shù)將字符串轉(zhuǎn)換為整數(shù):#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "123";
int num = atoi(str);
printf("轉(zhuǎn)換后的整數(shù)為:%d\n", num);
return 0;
}
atof()
函數(shù)將字符串轉(zhuǎn)換為浮點(diǎn)數(shù):#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14";
float num = atof(str);
printf("轉(zhuǎn)換后的浮點(diǎn)數(shù)為:%f\n", num);
return 0;
}
sscanf()
函數(shù)根據(jù)格式化字符串將字符串轉(zhuǎn)換為數(shù)字:#include <stdio.h>
int main() {
char str[] = "123";
int num;
sscanf(str, "%d", &num);
printf("轉(zhuǎn)換后的整數(shù)為:%d\n", num);
return 0;
}
以上三種方法都可以將字符串轉(zhuǎn)換為數(shù)字,選擇使用哪一種方法取決于具體的需求和字符串的格式。