C语言字符串转数字的几种方法

在c语言中,字符串转数字是开发中常见的需求,这里介绍5种字符串转数字的方法,

其中atoi()函数,atof()函数,strtol()函数分别将字符串转为整数int、浮点数float、长整数long,

sscanf()函数为格式化输入的方式,另外增加自定义函数的方式将字符串转为数字。

下面通过例子介绍每种方法的转换。

1. 使用atoi()函数(字符串转整数)

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

int main() {
    const char *str = "12345";
    int num = atoi(str);
    
    printf("使用atoi()转换:\n");
    printf("字符串: \"%s\" -> 整数: %d\n", str, num);
    
    return 0;
} 

输出结果

使用atoi()转换:
字符串: "12345" -> 整数: 12345

2. 使用atof()函数(字符串转浮点数)

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

int main() {
    const char *str = "123.456";
    double num = atof(str);
    
    printf("使用atof()转换:\n");
    printf("字符串: \"%s\" -> 浮点数: %f\n", str, num);
    
    return 0;
}
输出结果
使用atof()转换:
字符串: "123.456" -> 浮点数: 123.456000

3. 使用strtol()函数(字符串转长整数,可指定进制)

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

int main() {
    const char *str = "1010";
    char *endptr;
    long num = strtol(str, &endptr, 2); // 二进制转换
    
    printf("使用strtol()转换:\n");
    printf("二进制字符串: \"%s\" -> 十进制整数: %ld\n", str, num);
    
    return 0;
}
输出结果
使用strtol()转换:
二进制字符串: "1010" -> 十进制整数: 10

4. 使用sscanf()函数(格式化输入)

 #include <stdio.h>

int main() {
    const char *str = "9876";
    int num;
    sscanf(str, "%d", &num);
    
    printf("使用sscanf()转换:\n");
    printf("字符串: \"%s\" -> 整数: %d\n", str, num);
    
    return 0;
} 

输出结果

使用sscanf()转换:
字符串: "9876" -> 整数: 9876 

5.使用自定义函数

 #include <stdio.h>
#include <ctype.h>

int string_to_int(const char *str) {
    int result = 0;
    int sign = 1;
    
    // 处理符号
    if (*str == '-') {
        sign = -1;
        str++;
    }
    
    // 逐个字符转换
    while (*str != '\0') {
        if (!isdigit(*str)) {
            break; // 遇到非数字字符停止
        }
        result = result * 10 + (*str - '0');
        str++;
    }
    
    return sign * result;
}

int main() {
    const char *str = "-54321";
    int num = string_to_int(str);
    
    printf("手动实现转换:\n");
    printf("字符串: \"%s\" -> 整数: %d\n", str, num);
    
    return 0;
} 
输出
手动实现转换:
字符串: "-54321" -> 整数: -54321

注意事项 

atoi()和atof()没有错误检查,如果字符串无效会返回0 

strtol()和strtod()系列函数提供了更好的错误处理能力 

对于需要精确控制的转换,建议使用sscanf()或手动实现 

在C99及以上版本,还可以使用strtoll()、strtoull()等函数