在C語言中可以使用atoi
函數(shù)將字符串轉(zhuǎn)換為整數(shù)。atoi
函數(shù)的原型如下:
int atoi(const char *str);
atoi
函數(shù)將參數(shù)str
指向的字符串轉(zhuǎn)換為一個整數(shù)并返回。具體的實現(xiàn)如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("The converted integer is %d\n", num);
return 0;
}
輸出結(jié)果:
The converted integer is 12345
注意,atoi
函數(shù)會忽略字符串中的空格字符,并且當(dāng)字符串無法轉(zhuǎn)換為整數(shù)時,atoi
函數(shù)會返回0。