c语言字符串转数字如何实现

   2024-10-20 8220
核心提示:在C语言中,可以使用库函数atoi或strtol来实现字符串转换为数字的功能。使用atoi函数:#include stdio.h#include stdlib.hint ma

在C语言中,可以使用库函数atoistrtol来实现字符串转换为数字的功能。

使用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函数更加灵活,可以处理更多的异常情况,比如字符串中包含非数字字符。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号