推荐使用 std::to_string 将数字转字符串,支持 int、double 等类型,简单安全;2. 可用 stringstream 实现灵活格式化转换;3. 字符串转数字常用 std::stoi、std::stod 等函数,会抛异常需捕获;4. C++17 起可用 std::from_chars 进行高效无异常解析。

在C++中,将数字转换为字符串是常见的操作。现代C++提供了多种简洁安全的方法来实现这一功能,同时也支持反向转换。以下是常用的数字与字符串相互转换方式。
使用 to_string 函数(推荐)
C++11 起引入了 std::to_string,可将常见数值类型直接转为字符串。
- 支持 int、long、float、double 等基本类型
- 用法简单,无需额外库
示例代码:
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::to_string(num);
double d = 3.14159;
std::string str2 = std::to_string(d);
std::cout << str << std::endl; // 输出: 123
std::cout << str2 << std::endl; // 输出: 3.141590(注意精度)
return 0;
}
注意:to_string 对浮点数的默认精度较高,可能包含多余小数位,必要时可配合 setprecision 使用。
立即学习“C++免费学习笔记(深入)”;
使用 stringstream 流处理
通过 std::stringstream 可以灵活地进行类型转换,适合复杂格式化场景。
步骤如下:
- 创建 stringstream 对象
- 使用 << 操作符写入数字
- 调用 str() 获取字符串结果
示例:
#include <sstream>
#include <string>
#include <iostream>
int main() {
int num = 456;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl; // 输出: 456
return 0;
}
优点是可组合多个值,例如:ss << "Value: " << num;
字符串转数字的方法
除了数字转字符串,反过来也有几种常用方式:
- std::stoi:转为 int
- std::stol:转为 long
- std::stof:转为 float
- std::stod:转为 double
示例:
std::string str = "789";
int num = std::stoi(str);
double d = std::stod("3.14");
这些函数定义在 <string> 头文件中,会抛出异常(如 invalid_argument 或 out_of_range),使用时建议加 try-catch。
使用 from_string 的替代方案(C++17 起)
C++17 引入了 std::from_chars,提供更高效、无异常的解析方式,适用于性能敏感场景。
不过它语法稍复杂,通常用于避免异常或需要精确控制解析过程的情况。
基本上就这些常用方法。日常开发中,std::to_string 和 std::stoi/stod 已能满足大多数需求,简单直接。stringstream 更适合格式化输出。选择哪种方式取决于具体场景和C++标准支持程度。











