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;
}
本文介绍了一种使用stringstream实现不同类型间转换的通用模板函数,并通过示例展示了如何将整型、浮点型等基本数据类型转换为字符串,以及如何将字符串转换回原始的数据类型。
1万+

被折叠的 条评论
为什么被折叠?



