跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

C++ 如何将整数转换为字符串_C++ int 转 string 的多种实现方式

C++中整数转字符串常用方法包括:①std::to_string(C++11,简洁高效);②stringstream(兼容性好,灵活性高);③std::format或fmt库(C++20,性能佳);④boost::lexical_cast(类型安全,需引入Boost)。推荐优先使用std::to_string。

在 C++ 中,将整数(int)转换为字符串(string)是常见的操作。有多种方式可以实现这一转换,每种方法都有其适用场景和特点。以下是几种常用且有效的方法。

使用 std::to_string这是最简单直接的方式,C++11 起引入了std::to\_string函数,支持基本数据类型到字符串的转换。

用法简单,一行代码即可完成转换适用于 int、long、float、double 等数值类型不需要引入额外的头文件(除 外)

示例代码:

Python 3.14.3微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。

下载#include #include int main() {int num = 123;std::string str = std::to_string(num);std::cout << str << std::endl; // 输出: 123 return 0;}使用 stringstream std::stringstream是一种更传统的方法,通过流操作将整数插入字符串流中,再提取为 string。

立即学习“C++免费学习笔记(深入)

”;

兼容性好,适用于早期 C++ 标准可组合多个不同类型的数据到一个字符串中性能略低于 to_string,但灵活性更高

示例代码:

#include #include #include int main() {int num = 456;std::stringstream ss;ss << num;std::string str = ss.str();std::cout << str << std::endl; // 输出: 456 return 0;}使用 fmt 库(现代 C++ 推荐)

如果你使用的是较新的项目,可以考虑引入fmt库(也集成在 C++20 的 std::format 中),它提供高性能格式化功能。

C++20 开始支持 std::format,语法类似 Pythonfmt 库性能优异,广泛用于高性能场景需要额外安装或启用 C++20 支持

示例(C++20):

#include #include #include int main() {int num = 789;std::string str = std::format("{}", num);std::cout << str << std::endl; // 输出: 789 return 0;}使用 boost::lexical_cast(第三方库)

Boost 提供了boost::lexical\_cast,可以安全地在不同类型间转换。

语法简洁,类型安全需要链接 Boost 库,增加依赖异常处理机制完善,转换失败会抛出异常

示例代码:

#include #include #include int main() {try {int num = 100;std::string str = boost::lexical_cast(num);std::cout << str << std::endl;} catch (const boost::bad_lexical_cast&) {std::cerr << "转换失败" << std::endl;}return 0;}基本上就这些常见方式。日常开发中推荐优先使用std::to_string,简单高效;若追求性能或格式控制,可考虑fmt或std::format;维护旧项目时stringstream依然可靠。选择哪种方式取决于你的编译器支持和项目需求。

相关文章