C++里 int 转 string 的几种写法
在 C++ 里把 int 转成 string,日常写代码经常会碰到。能用的方法也就那么几种,这里简单整理一下,方便以后自己回查。
C++11 之后最省事的办法就是 std::to_string。
一句搞定,参数丢进去直接出 std::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;
}
不过 to_string 只适合单个数值,如果同时还要往里塞其他东西,比如拼一句日志,用流操作会更顺手。
std::stringstream 就是专门干这个的,支持各种类型的 << 操作,最后调 str() 一把拿到字符串。用法和 cout 一样,上手没什么成本。
#include <sstream>
#include <string>
#include <iostream>
int main() {
int num = 123;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl; // 输出: 123
return 0;
}
如果你只是想拼接字符串,不打算再从流里读东西,那换成 std::ostringstream 会更明确一点——光看类名就知道它只负责输出,不会误用成输入流。使用方式和 stringstream 几乎一样:
#include <sstream>
#include <string>
#include <iostream>
int main() {
int num = 123;
std::ostringstream oss;
oss << num;
std::string str = oss.str();
std::cout << str << std::endl; // 输出: 123
return 0;
}
如果你的项目已经能上 C++20,std::format 非常值得用。格式化字符串那一套很像 Python 的 format,类型安全,不会像 sprintf 那样写错格式符就炸。哪怕只是单纯转个数字,也比 to_string 更灵活,比如控制宽度、填充字符,都可以在一个地方搞定。
#include <format>
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::format("{}", num);
std::cout << str << std::endl; // 输出: 123
return 0;
}
说到 sprintf,在一些老项目或者嵌入式环境里还是很常见。
虽然现在 C++ 不推荐这么写了,但如果需要兼容旧代码或者 C 风格的接口,知道它怎么回事也没什么坏处。用的时候最大的坑就是缓冲区长度——必须手动定一个 char 数组,长度不够就溢出了,定位起来很费劲。下面是个最基本的用法:
#include <cstdio>
#include <string>
#include <iostream>
int main() {
int num = 123;
char buffer[20];
std::sprintf(buffer, "%d", num);
std::string str = buffer;
std::cout << str << std::endl; // 输出: 123
return 0;
}
实际写的话,如果确实要留在 C 风格里,至少换成 snprintf 来控制最大长度,心里会踏实一点。不过那就是另一个话题了。
总之,能上 C++20 就直接 std::format,省心且现代;退一步用 std::to_string,简洁明了;需要临时拼字符串的时候,流操作仍然是很好的选择。
至于 sprintf,除非维护老代码,不然平时写新功能就尽量别主动用了。
SSL证书申请支持自动验证、自动部署功能!lcjmSSL提供完整的自动化能力。无论个人开发者还是初创团队,都能享受企业级的证书管理体验。

浙公网安备 33010602011771号