最简单的方法是使用std::to_string,C++11起支持将整数转为字符串,用法简洁;也可用stringstream进行灵活格式化;现代C++推荐fmt库实现高效转换,性能好且语法清晰。

在C++中,将整数转换为字符串有多种方法,下面介绍几种常用且简单的方式,适用于不同场景。
使用 std::to_string
这是最简单直接的方法。C++11 起提供了 std::to_string 函数,可以将整数(以及其他数值类型)轻松转换为字符串。
- 支持 int、long、long long、float、double 等类型
- 用法简洁,推荐日常使用
示例代码:
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout <h3>使用 string<a style="color:#f60; text-decoration:underline;" title="stream" href="https://m.php.cn/zt/19633.html" target="_blank">stream</a>
</h3>
<p>利用 <strong>std::stringstream</strong> 可以实现更灵活的格式化转换,适合需要拼接或格式控制的场景。</p>
<font color="#000000">
<ul>
<li>包含头文件 <sstream></sstream>
</li>
<li>通过插入操作符
</li>
</ul></font><p><strong>示例代码:</strong></p>
<pre class="brush:php;toolbar:false;">#include <sstream>
#include <string>
#include <iostream>
int main() {
int num = 456;
std::stringstream ss;
ss <h3>使用 fmt 库(现代C++推荐)</h3>
<p>如果你使用 C++20 或引入了 <strong>fmt</strong> 第三方库(高性能格式化),可以用 <strong>fmt::format</strong> 实现高效转换。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Livestream Sales Script" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script" class="overflowclass">Livestream Sales Script</a>
<p class="overflowclass">直播带货脚本专家,擅长根据产品信息编写生动、吸引人且具说服力的直播脚本,突出核心卖点。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p>优点:性能高,语法清晰,支持复杂格式。</p>
<p><strong>示例:</strong></p>
<pre class="brush:php;toolbar:false;">#include <fmt>
#include <string>
#include <iostream>
int main() {
int num = 789;
std::string str = fmt::format("{}", num);
std::cout <h3>手动实现(不推荐但可学习)</h3>
<p>对于学习目的,也可以通过循环取余方式逐位转换,再反转字符串。但实际开发中没必要手写,效率低且易错。</p>
<p>基本上就这些常见方法。日常开发推荐优先使用 <strong>std::to_string</strong>,简单明了。如果项目中已有 fmt 库,也可用它获得更好性能和一致性。</p></iostream></string></fmt>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










