温馨提示×

c语言字符转换为数字怎么实现

小亿
151
2024-03-25 17:54:51
栏目: 编程语言

在C语言中,可以使用标准库函数atoistrtol来将字符转换为数字。

  1. 使用atoi函数:
#include <stdio.h> #include <stdlib.h> int main() { char c = '5'; int num = atoi(&c); printf("转换后的数字为: %d\n", num); return 0; } 
  1. 使用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函数可以将字符串转换为长整型,并具有更多的参数选项。

0