在C语言中,可以使用库函数atoi或strtol来实现字符串转换为数字的功能。
atoi函数:#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函数:#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;}这两种方法都可以将字符串转换为对应的整数,但是strtol函数更加灵活,可以处理更多的异常情况,比如字符串中包含非数字字符。




