Linux 拨号vps windows公众号手机端

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

lewis 9年前 (2016-11-08) 阅读数 9 #程序编程
文章标签 c语言

在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函数可以将字符串转换为长整型,并具有更多的参数选项。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门