当前位置: 首页 > article >正文

【C++奇迹之旅】:字符串转换成数字将数字转换成字符串大全

加粗样式
请添加图片描述

文章目录

  • 📝字符串转换成数字
      • 1. 使用标准库函数
        • 转换为整数
        • 转换为浮点数
      • 2. 使用 `std::strtol`、`std::strtod` 等 C 风格函数
      • 3. 使用 `std::stringstream`
  • 🌉将数字转换成字符串
      • 1. 使用 `std::to_string` 函数
      • 2. 使用 `std::stringstream`
      • 3. 使用 C 风格的函数(如 `sprintf` 或 `snprintf`)
      • 4. 使用 `std::format`(C++20 及以后)
  • 🚩总结


📝字符串转换成数字

在 C++ 里,把字符串转换成数字有多种方式,下面针对不同的数据类型和使用场景详细介绍具体

1. 使用标准库函数

转换为整数

可以使用 std::stoi(转换为 int 类型)、std::stol(转换为 long 类型)、std::stoll(转换为 long long 类型)等函数。这些函数定义在 <string> 头文件中。

#include <iostream>
#include <string>

int main() {
    std::string strInt = "12345";
    try {
        int numInt = std::stoi(strInt);
        std::cout << "Converted to int: " << numInt << std::endl;

        long numLong = std::stol(strInt);
        std::cout << "Converted to long: " << numLong << std::endl;

        long long numLongLong = std::stoll(strInt);
        std::cout << "Converted to long long: " << numLongLong << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cout << "Invalid argument: " << e.what() << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Out of range: " << e.what() << std::endl;
    }
    return 0;
}

解释

  • std::stoistd::stolstd::stoll 函数会尝试将字符串转换为对应的整数类型。
  • 如果字符串不能正确转换为数字,会抛出 std::invalid_argument 异常;如果转换后的数字超出了目标类型的范围,会抛出 std::out_of_range 异常。
转换为浮点数

可以使用 std::stof(转换为 float 类型)、std::stod(转换为 double 类型)、std::stold(转换为 long double 类型)等函数。

#include <iostream>
#include <string>

int main() {
    std::string strFloat = "3.14159";
    try {
        float numFloat = std::stof(strFloat);
        std::cout << "Converted to float: " << numFloat << std::endl;

        double numDouble = std::stod(strFloat);
        std::cout << "Converted to double: " << numDouble << std::endl;

        long double numLongDouble = std::stold(strFloat);
        std::cout << "Converted to long double: " << numLongDouble << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cout << "Invalid argument: " << e.what() << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Out of range: " << e.what() << std::endl;
    }
    return 0;
}

解释

  • std::stofstd::stodstd::stold 函数用于将字符串转换为对应的浮点数类型。
  • 同样,若字符串无法正确转换,会抛出 std::invalid_argument 异常;若结果超出范围,会抛出 std::out_of_range 异常。

2. 使用 std::strtolstd::strtod 等 C 风格函数

这些函数定义在 <cstdlib> 头文件中,是 C 语言遗留下来的函数,在 C++ 中也可以使用。

#include <iostream>
#include <cstdlib>

int main() {
    const char* strInt = "23456";
    char* endptr;
    long numLong = std::strtol(strInt, &endptr, 10);
    if (*endptr == '\0') {
        std::cout << "Converted to long using strtol: " << numLong << std::endl;
    } else {
        std::cout << "Conversion error: not a valid number." << std::endl;
    }

    const char* strFloat = "2.71828";
    double numDouble = std::strtod(strFloat, &endptr);
    if (*endptr == '\0') {
        std::cout << "Converted to double using strtod: " << numDouble << std::endl;
    } else {
        std::cout << "Conversion error: not a valid number." << std::endl;
    }

    return 0;
}

解释

  • std::strtol 用于将字符串转换为 long 类型,std::strtod 用于将字符串转换为 double 类型。
  • endptr 是一个指向字符的指针,函数会将其设置为字符串中第一个无法转换为数字的字符的位置。如果 *endptr 是字符串结束符 '\0',则表示整个字符串都被成功转换。

3. 使用 std::stringstream

std::stringstream 定义在 <sstream> 头文件中,可以实现字符串和各种数据类型之间的转换。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string str = "456";
    int num;
    std::stringstream ss(str);
    if (ss >> num) {
        std::cout << "Converted to int using stringstream: " << num << std::endl;
    } else {
        std::cout << "Conversion error using stringstream." << std::endl;
    }

    std::string strFloat = "5.67";
    double numDouble;
    std::stringstream ssFloat(strFloat);
    if (ssFloat >> numDouble) {
        std::cout << "Converted to double using stringstream: " << numDouble << std::endl;
    } else {
        std::cout << "Conversion error using stringstream." << std::endl;
    }

    return 0;
}

解释

  • 首先创建一个 std::stringstream 对象,并将字符串传递给它。
  • 然后使用 >> 运算符将字符串流中的内容提取到目标变量中。如果提取成功,>> 运算符返回 true;否则返回 false

综上所述,在 C++ 中可以根据具体需求和场景选择合适的方法将字符串转换为数字。通常情况下,使用标准库函数(如 std::stoistd::stod 等)是比较简洁和安全的方式。

🌉将数字转换成字符串

1. 使用 std::to_string 函数

std::to_string 是 C++11 引入的标准库函数,它可以将整数(如 intlonglong long 等)和浮点数(如 floatdoublelong double 等)转换为 std::string 类型。该函数定义在 <string> 头文件中。

#include <iostream>
#include <string>

int main() {
    // 整数转换
    int numInt = 123;
    std::string strInt = std::to_string(numInt);
    std::cout << "Integer converted to string: " << strInt << std::endl;

    // 浮点数转换
    double numDouble = 3.14;
    std::string strDouble = std::to_string(numDouble);
    std::cout << "Double converted to string: " << strDouble << std::endl;

    return 0;
}

解释

  • std::to_string 函数会根据传入的数字类型自动处理转换,使用起来非常方便。
  • 对于浮点数,转换后的字符串会包含一定的小数位数,具体位数可能因编译器和系统而异。

2. 使用 std::stringstream

std::stringstream 是 C++ 标准库中的流类,定义在 <sstream> 头文件中,可用于在字符串和各种数据类型之间进行转换。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    // 整数转换
    int numInt = 456;
    std::stringstream ssInt;
    ssInt << numInt;
    std::string strInt = ssInt.str();
    std::cout << "Integer converted to string using stringstream: " << strInt << std::endl;

    // 浮点数转换
    double numDouble = 2.718;
    std::stringstream ssDouble;
    ssDouble << numDouble;
    std::string strDouble = ssDouble.str();
    std::cout << "Double converted to string using stringstream: " << strDouble << std::endl;

    return 0;
}

解释

  • 首先创建一个 std::stringstream 对象。
  • 使用 << 运算符将数字插入到 stringstream 中。
  • 最后调用 str() 方法获取 stringstream 中的字符串内容。

3. 使用 C 风格的函数(如 sprintfsnprintf

sprintfsnprintf 是 C 语言中的格式化输出函数,在 C++ 中也可以使用。它们定义在 <cstdio> 头文件中。

#include <iostream>
#include <cstdio>
#include <string>

int main() {
    // 整数转换
    int numInt = 789;
    char bufferInt[20];
    std::sprintf(bufferInt, "%d", numInt);
    std::string strInt(bufferInt);
    std::cout << "Integer converted to string using sprintf: " << strInt << std::endl;

    // 浮点数转换
    double numDouble = 1.618;
    char bufferDouble[20];
    std::sprintf(bufferDouble, "%f", numDouble);
    std::string strDouble(bufferDouble);
    std::cout << "Double converted to string using sprintf: " << strDouble << std::endl;

    return 0;
}

解释

  • sprintf 函数将数字按照指定的格式(如 %d 表示整数,%f 表示浮点数)写入到字符数组中。
  • 然后使用字符数组构造 std::string 对象。

4. 使用 std::format(C++20 及以后)

std::format 是 C++20 引入的格式化字符串函数,它提供了一种简洁且类型安全的方式来进行字符串格式化,包括数字到字符串的转换。该函数定义在 <format> 头文件中。

#include <iostream>
#include <format>

int main() {
    // 整数转换
    int numInt = 999;
    std::string strInt = std::format("{}", numInt);
    std::cout << "Integer converted to string using std::format: " << strInt << std::endl;

    // 浮点数转换
    double numDouble = 0.577;
    std::string strDouble = std::format("{}", numDouble);
    std::cout << "Double converted to string using std::format: " << strDouble << std::endl;

    return 0;
}

解释

  • std::format 函数使用占位符 {} 来表示要插入的值,会自动将数字转换为字符串并插入到指定位置。
  • 这种方式代码简洁,且类型安全,避免了一些传统格式化函数可能出现的错误。

🚩总结

请添加图片描述


http://www.kler.cn/a/567063.html

相关文章:

  • 深度学习五大模型:CNN、Transformer、BERT、RNN、GAN详细解析
  • Android15 am命令 APP安装流程
  • anaconda配置pytorch
  • C++ primer plus 第四节 复合类型
  • 深入解析 Svelte:下一代前端框架的革命
  • 前端实现上传图片到OSS(Vue3+vant)
  • 《深入浅出 Vue.js 组件化开发》
  • 设计一个“车速计算”SWC,通过Sender-Receiver端口输出车速信号。
  • Prometheus + Grafana 监控
  • 解决“两数之和”问题:两种实现方法详解
  • 双臂机器人的动力学建模
  • 浅入浅出Selenium DevTools
  • Oracle日常管理(8)——DB日常管理(2)
  • 正大杯攻略|量表类问卷数据分析基本步骤
  • Html5学习教程,从入门到精通,HTML 5 图像语法知识点语法知识点及案例代码(9)
  • #深入了解DNS3和VCTK语音数据集
  • 模拟器游戏多开为什么需要单窗口单IP
  • MES:开启生产制造优秀管理新时代
  • 博客系统完整开发流程
  • LeetCode 每日一题 2025/2/24-2025/3/2