使用stringstream简化类型转换

<sstream>库定义了istringstream、ostringstream和stringstream三种类,用于流的输入、输出和输入输出操作。通过重载,支持自定义类型间的转换,提高效率并避免缓冲区溢出。示例展示了如何使用模板函数将任意类型转换为字符串或特定目标类型。

<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。
注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。

重复利用stringstream对象,记住在每次转换前要使用clear()方法。

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

在类型转换中使用模板,可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。

基于stringstream的转换拥有类型安全和不会溢出这样的特性,使我们有充足得理由去使用<sstream>。<sstream>库还提供了另外一个特性—可扩展性。可以通过重载来支持自定义类型间的转换。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template<class T>
void to_string(string &result, const T &t)//将任意值t转换为字符串并写入result中
{

	ostringstream oss;//创建一个流
	oss << t;//把值传递入流中
	result = oss.str();//获取转换后的字符并将其写入result中
}

//定义一个通用的转换模板,用于任意类型之间的转换。
//函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型
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;
}

int main()
{
	//to_string实例
	string s1, s2, s3;

	to_string(s1, 10.5);  //double到string
	to_string(s2, 123);  //int到string
	to_string(s3, true);  //bool到string
	cout << s1 << endl << s2 << endl << s3 << endl << endl;

	//convert()例子
	double d;
	string sa;
	string s = "12.56";

	d = convert <double>(s);  //d等于12.56
	sa = convert <string>(9000.0); //sa等于"9000"

	cout << d << endl << sa << endl;

	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值