C++ 标准库中数据类型转换

头文件引用:

<sstream>

<sstream>库定义了三种类:

istringstream:处理流的输入

ostringstream:处理流的输出

stringstream:处理流的输入输出

简单起见,这里主要以stringstream为中心进行简单描述:

例1:string转int

stringstream stream;
string s = "100";
int i = 0;
stream << s;
stream >> i;// 结果i等于100

例2:int转string

stringstream stream;
string s = "";
int i = 100;
stream << i;
s = stream.str();// 结果s等于"100"

针对如上示例,可以写一简单的通用转换函数。

函数1:任意数据类型转换为string类型

template<class T>
void to_string(string& out, constT& in)
{
    stringstream stream;
    stream << in;
    out = stream.str();
}

或
template<class T>
string to_string(constT& in)
{
    stringstream stream;
    stream << in;
    string out;
    out = stream.str();
    return out;
}

函数2:string转换为任意数据类型

template<class T>
void string_to(string& in, constT& out)
{
    stringstream stream;
    stream << in;
    stream >> out;
}

或
template<class T>
T string_to(string& in)
{
    stringstream stream;
    stream << in;
    T out;
    stream >> out;
    return out;
}

函数3:任意数据类型转换为string类型

template<class out_type,class in_value>
out_type format(const in_value& in)
{
	stringstream stream;
	stream << in;
	out_type out;
	stream >> out;
	return out;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值