c语言

c语言怎么把字符串转换成数字

小亿
135
2024-04-09 19:02:35
栏目: 编程语言
C语言开发专用服务器,限时0元免费领! 查看>>

在C语言中,可以使用标准库函数atoi()strtol()来将字符串转换成数字。

  1. 使用atoi()函数:
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    int num = atoi(str);
    
    printf("The converted number is: %d\n", num);

    return 0;
}
  1. 使用strtol()函数:
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    long num = strtol(str, NULL, 10);
    
    printf("The converted number is: %ld\n", num);

    return 0;
}

其中,strtol()函数可以将字符串转换成长整型数字,第一个参数为要转换的字符串,第二个参数为一个指针,用于存放转换后的字符串的结尾位置,第三个参数为转换的基数,一般为10。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:php字符串怎么转换成数字

0
看了该问题的人还看了