C++标准库<sstream>中的stringstream
<sstream>库
- <sstream>库定义了三种类:
istringstream、ostringstream 和 stringstream
,分别用来进行流的输入、输出和输入输出操作。 - 基于该类的转换拥有类型安全和不会溢出的特性。还可以通过重载来支持自定义类型间的转换。
- 如果你打算在多次转换中使用同一个流对象,记住再每次转换前要使用
clear()
方法;
<1> ostringstream
将 int、long、double
等类型转换成字符串string
类型。
1 2 3 4 5 6 | template < class T> void to_string(string & result, const T& t){ ostringstream oss; //创建一个流 oss<<t; //把值传递如流中 result=oss.str(); //获取转换后的字符转并将其写入result } |
<2>istringstream
字符串转基本类型
1 2 3 4 | istringstream iss; iss.str( "123" ); //或者直接构造 istringstream iss2("123 456"); int n; iss >> n; |
<3>stringstream
1. 任意类型之间的转换。将in_value值转换成out_type类型
1 2 3 4 5 6 7 8 | template < class out_type, class in_value> out_type convert( const in_value & t){ stringstream stream; stream<<t; //向流中传值 out_type result; //这里存储转换结果 stream>>result; //向result中写入值 return result; } |
2. 可以将数值类型转为十六进制字符串类型
1 2 3 4 5 6 7 8 9 | void test() { int num = -10; stringstream ss; ss << hex << uppercase << num; string ans; ss >> ans; cout << ans; } |
3. 将二进制字符串转为十进制数字
1 2 3 4 5 6 7 8 9 | int BToD( const string & binaryString) { stringstream ss; int result; int temp = stol(binaryString, NULL, 2); // 将字符串转为二进制 ss << dec << temp; // 将二进制转为十进制, 存入流中 ss >> result; return result; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?