c语言字符转换为数字怎么实现
在C语言中,可以使用标准库函数atoi
或strtol
来将字符转换为数字。
- 使用
atoi
函数:#include <stdio.h>#include <stdlib.h>int main() {char c = '5';int num = atoi(&c);printf("转换后的数字为: %d\n", num);return 0;}
- 使用
strtol
函数:#include <stdio.h>#include <stdlib.h>int main() {char c = '5';int num = (int)strtol(&c, NULL, 10);printf("转换后的数字为: %d\n", num);return 0;}
以上两种方法都可以将字符'5'
转换为数字5
。需要注意的是,atoi
函数只能将字符串转换为整数,而strtol
函数可以将字符串转换为长整型,并具有更多的参数选项。