
在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++免费学习笔记(深入)”;
- 包含头文件
- 创建 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风格)
适用于对性能要求高或嵌入式环境,但需注意缓冲区溢出问题。
标签: c++ 类型转换 ai ios stream 格式化输出 标准库
还木有评论哦,快来抢沙发吧~