C/C++数字字符串转换全指南

好的,这是一个在编程中常见的问题。以下是 C 和 C++ 中数字与字符串互相转换的主要方法:

一、数字转字符串

1. C 语言方法
  • sprintf / snprintf (安全推荐) 这是最常用的方法,类似于 printf,但输出到字符串缓冲区。
    #include <stdio.h>
    int num = 123;
    double dnum = 45.67;
    char str_int[20];
    char str_double[20];
    sprintf(str_int, "%d", num); // 整数转字符串
    snprintf(str_double, sizeof(str_double), "%.2f", dnum); // 浮点数转字符串,控制格式更安全
    

2. C++ 语言方法 (更现代、安全)
  • std::to_string (C++11 起) 这是最简单的方式,支持基本数值类型。
    #include <string>
    int num = 123;
    double dnum = 45.67;
    std::string str_int = std::to_string(num);
    std::string str_double = std::to_string(dnum); // 注意默认精度可能较高
    

  • std::ostringstream 更灵活,可以像使用 cout 一样输出各种类型和格式。
    #include <sstream>
    #include <string>
    int num = 123;
    double dnum = 45.67;
    std::ostringstream oss;
    oss << num << " and " << std::fixed << std::setprecision(2) << dnum;
    std::string result = oss.str(); // "123 and 45.67"
    

二、字符串转数字

1. C 语言方法
  • atoi, atol, atof 简单但不够安全(无法检测无效输入,出错返回 0 或 0.0)。
    #include <stdlib.h>
    const char* str_int = "123";
    const char* str_double = "45.67";
    int i = atoi(str_int);
    double d = atof(str_double);
    

  • strtol, strtoul, strtod (安全推荐) 更安全,能检测错误和指定进制。
    #include <stdlib.h>
    #include <errno.h>
    const char* str_num = "123abc";
    char* endptr;
    long l = strtol(str_num, &endptr, 10); // 十进制
    if (errno != 0 || *endptr != '\0') {
        // 转换出错或未消耗完整个字符串
    }
    
2. C++ 语言方法 (更现代、安全)
  • std::stoi, std::stol, std::stod 等 (C++11 起) 直接、方便,遇到无效输入会抛出 std::invalid_argumentstd::out_of_range 异常。
    #include <string>
    std::string str_int = "123";
    std::string str_double = "45.67";
    try {
        int i = std::stoi(str_int);
        double d = std::stod(str_double);
    } catch (const std::invalid_argument& e) {
        // 字符串无法转换
    } catch (const std::out_of_range& e) {
        // 数字超出范围
    }
    

  • std::istringstream 更灵活,可以像使用 cin 一样读取字符串中的数字。
    #include <sstream>
    #include <string>
    std::string input = "123 45.67";
    std::istringstream iss(input);
    int i;
    double d;
    if (iss >> i >> d) {
        // 读取成功
    } else {
        // 读取失败
    }
    

总结比较

转换方向语言方法特点
数字->字符串Csprintf/snprintf灵活,需注意缓冲区大小 (snprintf 更安全)
C++std::to_string简单直接
C++std::ostringstream最灵活,可控制格式
字符串->数字Catoi/atof简单但不安全 (无法检测错误)
Cstrtol/strtod较安全,可检测错误和指定进制
C++std::stoi/std::stod直接方便,通过异常处理错误
C++std::istringstream灵活,可从字符串流中提取多个值

建议:

  • 在 C++ 项目中,优先使用 C++11 引入的 std::to_stringstd::stox 系列函数,它们更安全、更简洁。
  • 需要更精细控制格式或从字符串中提取多个值时,考虑使用 std::ostringstreamstd::istringstream
  • 在纯 C 环境或旧代码中,务必使用 snprintfstrtol/strtod 等更安全的版本,避免 sprintfatoi 的安全隐患。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值