转基本数据类型之间的任意转换

template<class out_type,class in_value>

out_type convert(const in_value &t)

 

{

stringstream stream;

stream.clear();//清空流

stream << t;//向流中传值

out_type result;//这里存储转换结果

stream >> result;//向result中写入值

 

return result;

 

}

 

利用stringstream流的输入输出可以将基本数据类型转化为其他类型。

 

整个可以利用下列程序进行测试,在这里没用加防错及纠错处理,敬请见谅。

 

#include <cstdlib>

#include <string>

#include <iostream>

#include <sstream>

 

using namespace std;

 

template<class out_type,class in_value> out_type convert(const in_value &t);

 

int main(){

 

 

int i = 100;

double d = 111.1;

float f = 1.0f;

string iStr = convert<string, int>(i);

string fStr = convert<string, float>(f);

string dStr = convert<string, double>(d);

 

cout << "After a convertion, " << endl;

 

cout << "the number is :" << iStr << endl;

cout << "the float is :" << fStr << endl;

cout << "the double is :" << dStr << endl;

 

cout << "After another convertion, " << endl;

 

 

int str2Int = convert<int, string>(iStr);

float str2f = convert<float, string>(fStr);

double str2d = convert<double, string>(dStr);

 

cout << "the number is :" << str2Int << endl;

cout << "the float is :" << str2f << endl;

cout << "the double is :" << str2d << endl;

 

 

 

return 0;

}

 

template<class out_type,class in_value>

out_type convert(const in_value &t)

 

{

stringstream stream;

 

stream.clear();//清空流

stream << t;//向流中传值

out_type result;//这里存储转换结果

stream >> result;//向result中写入值

 

return result;

 

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值