答案:C++中int转string常用方法有四种。1. std::to_string(推荐,C++11起),直接转换,简洁安全;2. stringstream(兼容老版本),通过流操作实现,适合格式控制;3. sprintf/snprintf(C风格),性能高但需防缓冲区溢出;4. std::format(C++20),类型安全,功能强大。均支持负数与边界值处理,日常推荐std::to_string。

在C++中,将int类型转换为string有多种方法。下面介绍几种常用且可靠的方式,适合不同场景使用。
1. 使用 std::to_string(推荐)
这是最简单直接的方法,C++11起支持,适用于大多数整型转字符串的场景。
- 只需调用 std::to_string() 函数,传入整数即可返回对应的字符串。
示例代码:
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl; // 输出: 123
return 0;
}
2. 使用 stringstream
通过字符串流对象将整数“写入”字符串,兼容性好,适合老版本C++或需要格式控制的场合。
立即学习“C++免费学习笔记(深入)”;
- 包含头文件 <sstream>
- 创建 std::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;
}
3. 使用 sprintf / snprintf(C风格)
适用于对性能要求高或嵌入式环境,但需注意缓冲区溢出问题。
- 使用字符数组存储结果,通过 sprintf 或更安全的 snprintf 格式化输出。
- 最后将字符数组转为 std::string。
示例代码:
#include <cstdio>
#include <string>
#include <iostream>
int main() {
int num = 789;
char buffer[32];
snprintf(buffer, sizeof(buffer), "%d", num);
std::string str(buffer);
std::cout << str << std::endl; // 输出: 789
return 0;
}
4. C++17 及以上:std::format(未来趋势)
如果你使用的是C++20编译器,可以尝试 std::format,功能强大且类型安全。
示例(C++20):
#include <format>
#include <string>
#include <iostream>
int main() {
int num = 1000;
std::string str = std::format("{}", num);
std::cout << str << std::endl; // 输出: 1000
return 0;
}
注意:需启用 -std=c++20 编译选项,并确认标准库支持(如GCC 13+)。
基本上就这些常用方法。日常开发推荐优先使用 std::to_string,简洁安全。遇到复杂格式化需求时,再考虑 stringstream 或 std::format。不复杂但容易忽略的是负数和边界值(如 INT_MIN)的正确处理,这些方法都能正常工作。











