Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >【C++奇迹之旅】:字符串转换成数字&&将数字转换成字符串&&大全

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

作者头像
学习起来吧
发布于 2025-03-02 14:25:38
发布于 2025-03-02 14:25:38
12710
代码可运行
举报
文章被收录于专栏:学习C/++学习C/++
运行总次数:0
代码可运行

📝字符串转换成数字

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

1. 使用标准库函数
转换为整数

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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 类型)等函数。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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++ 中也可以使用。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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> 头文件中,可以实现字符串和各种数据类型之间的转换。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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> 头文件中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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> 头文件中,可用于在字符串和各种数据类型之间进行转换。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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> 头文件中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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> 头文件中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#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 函数使用占位符 {} 来表示要插入的值,会自动将数字转换为字符串并插入到指定位置。
  • 这种方式代码简洁,且类型安全,避免了一些传统格式化函数可能出现的错误。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-03-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
1 条评论
热度
最新
可以,大佬,互粉一下
可以,大佬,互粉一下
回复回复点赞举报
推荐阅读
编辑精选文章
换一批
软考:数值转换知识点详解
进制转换是数值转换的基础,涉及到不同数制之间的相互转换。在计算机科学中,二进制是最基本的数制,因为计算机内部使用二进制来存储和处理数据。然而,人类更习惯于使用十进制,而十六进制则因其简洁性在表示二进制数据时非常常用。
码事漫谈
2025/04/24
200
软考:数值转换知识点详解
C++ stringstream 实现字符与数字之间的转换
字符串转数字 #include<iostream> #include <sstream> #include <string> using namespace std; int main() { //字符转数字 string str1 = "2018219"; string str2 = "2018.219";//浮点数转换后的有效数为6位 int num1 = 0; double num2 = 0.0; stringstream s; //
Aidol
2020/07/23
9600
【备忘录】c++ 整形浮点字符串 类型转换
一、C风格字符串 1.<stdlib.h>中的转换函数  atoi atol atoll itoa ltoa ultoa lltoa atof ecvt fcvt gcvt strtol strtoul strtoll strtod 2. sprintf  sscanf (功能更强大) 二、std::string 1.标准库转换函数  (using namespace std;) to_string stoi stol stoul stoll stoul stof stod stold 2.字符串流
ApacheCN_飞龙
2019/02/15
7100
c++ 常用函数
#include <strstrea.h>   //该类不再支持,改用<sstream>中的stringstream
用户7886150
2021/02/09
6700
C/C++数字与字符串互相转换
在C/C++程序中,会需要把数字与字符串做出互相转换的操作,用于实现程序想要的效果。下面将介绍多种方法实现数字与字符串互相转换。
摆烂小白敲代码
2024/09/23
1840
C/C++数字与字符串互相转换
C语言中你可能不熟悉的头文件(stdlib.h)
C Standard General Utilities Library (header)
Enjoy233
2019/03/05
1.6K0
C++ 11字符数组/字符串/数字转换/字符串拼接
缺点:处理大量数据转换速度较慢。stringstream不会主动释放内存,如果要在程序中用同一个流,需要适时地清除一下缓存,用stream.clear()
SL_World
2021/09/18
3.2K0
C++性能优化神器:它 比 std::stoi 快 3 倍!
我最近在项目中遇到一个需求——针对同一个类型的接口,需要支持传入多种数据类型,大概形式如下,
程序员的园
2025/04/01
700
C++性能优化神器:它 比 std::stoi 快 3 倍!
C++17 中的 std::to_chars 和 std::from_chars:高效且安全的字符串转换工具
在现代 C++ 开发中,字符串与数值之间的转换是一个常见的需求,尤其是在处理输入输出、数据解析和格式化时。C++17 引入了 std::to_chars 和 std::from_chars,这两个函数为开发者提供了高效、安全且灵活的字符串转换工具。
码事漫谈
2025/02/20
1112
C++17 中的 std::to_chars 和 std::from_chars:高效且安全的字符串转换工具
C\C++字符与数字的转换
核心思想: 整数转化为字符串:加 ‘0’ ,然后逆序。 字符串转化整数:减 ‘0’,乘以10累加。 注:整数加 ‘0’后会隐性的转化为char类型;字符减 ‘0’隐性转化为int类型
用户7886150
2021/02/08
5590
【C++篇】像解谜一样转换字符串:stoi 带你走向整数的世界
stoi 是 C++11 引入的一个标准库函数,常用于将字符串转换为整数。它的全称是 "string to integer"。
熬夜学编程的小王
2024/11/25
5380
C/CPP每日一题:Playing with digits
Some numbers have funny properties. For example:
CtrlX
2022/09/23
3890
C/CPP每日一题:Playing with digits
c++ 字符串流 sstream(常用于格式转换)
C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能,即单纯性、类型安全和可扩展性。在本文中,我将展示怎样使用这些库来实现安全和自动的类型转换。
全栈程序员站长
2022/09/05
1.1K0
C++数值类型与string的相互转换
std命令空间下有一个C++标准库函数std::to_string(),可用于将数值类型转换为string。使用时需要include头文件<string>。
恋喵大鲤鱼
2018/08/03
9.9K0
C++学习总结4——类型转换
在写程序的时候有时会遇到类型转换的问题,而这些问题的解答每次都记不住,每次都得上网查找,经常下来,也觉得很浪费时间。所以这里我把C语言和C++里面一些常用的类型转换方式写下来,一方面为了以后查找方便,另一方面也是希望通过敲一遍能尽可能地记住转换的思路。所有这些转换的代码我已经放到了github上,或许可以帮到你。
王云峰
2019/12/25
9260
C++ int与string的相互转换(含源码实现)
string to_string (unsigned long long val);
全栈程序员站长
2022/09/06
2K0
sstream类的详解
C++引入了ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含sstream.h头文件。
全栈程序员站长
2022/09/05
1.5K0
OpenCV4 C++开发筑基之数据转换
之前我写过一篇介绍学习OpenCV C++一些前置基础C++11的基础知识,主要是介绍了输出打印、各种常见数据容器。这里又整理了一篇,主要涉及各种数据类型之间的相互转换。用C++写代码,特别是写算法,很多时候会遇到各种精度的数据相互转换、显示的时候还会遇到不同类型变量相互转换,因此个人总结了一下,主要有以下三种常见的数据转换
OpenCV学堂
2024/03/07
1660
OpenCV4 C++开发筑基之数据转换
整型与字符串转换
我们写程序的时候经常会遇到整型和字符串相互转换的问题,这里要用到几个函数,itoa(),atoi(),sprintf()下面来介绍下这几个函数的具体用法!
全栈程序员站长
2022/09/06
9320
整型与字符串转换
C++之字符串
C语言中不提供字符串类型,因此所谓的字符串不过是一组以’\0’结尾的字符序列。 C语言中通常以char型的数组来存储字符串,如下例:
用户7886150
2021/02/16
6940
相关推荐
软考:数值转换知识点详解
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验