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

在C语言中,可以使用以下几种方法将字符转换为数字:

使用atoi()函数:该函数将字符串转换为整数。需要包含<stdlib.h>头文件。

#include <stdio.h>
#include <stdlib.h>

int main() {
    char c = '5';
    int num = atoi(&c);
    printf("%d\n", num);  // 输出:5
    
    return 0;
}

使用sscanf()函数:该函数将字符串按指定格式转换为特定类型的值。需要包含<stdio.h>头文件。

#include <stdio.h>

int main() {
    char c = '7';
    int num;
    sscanf(&c, "%d", &num);
    printf("%d\n", num);  // 输出:7
    
    return 0;
}

使用字符的ASCII码值进行转换:字符的ASCII码值减去字符’0’的ASCII码值,即可得到对应的数字。

#include <stdio.h>

int main() {
    char c = '9';
    int num = c - '0';
    printf("%d\n", num);  // 输出:9
    
    return 0;
}

以上是常用的字符转换为数字的方法,具体使用哪种方法取决于实际需求和个人习惯。

阅读剩余
THE END