// 013 sstream.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<sstream>
using namespace std;
//使用模板类型转换,任意类型->string的转换
template<class T>
void to_string(string & result,const T& t)
{
ostringstream oss; //创建一个流
oss<<t; //把值传递如流中
result=oss.str(); //str()成员函数来获取流内部缓冲的一份拷贝,获取转换后的字符转并将其写入result
}
//更进一步定义一个通用的转换模板,用于任意类型之间的转换
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(int argc, char* argv[])
{
//sprintf()函数将一个变量从int类型转换到字符串类型,但是容易出错,因为需要自己写格式
int n=10000;
char s[10];
sprintf(s,"%d",n); //s中内容为"10000"
cout<<s<<endl<<endl;
//string到int的转换
stringstream stream;
string result="10000";
int m=0;
stream<<result; //向流中传值,箭头方向即传值方向
stream>>m; //将流中的值传入m,m等于10000
cout<<m<<endl<<endl;
stream.clear(); //clear()之后可以重复使用stream,避免重复申请stringstream对象,节省时间
//使用模板类型转换,任意类型->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;
cout<<s2<<endl;
cout<<s3<<endl<<endl;
//基本类型的转换,也支持char *的转换。
// stringstream stream;
char ch[8] ;
stream << 8888; //向stream中插入8888
stream >> ch; //抽取stream中的值到result
cout << ch << endl<<endl; // 屏幕显示 "8888"
//更进一步定义一个通用的转换模板,用于任意类型之间的转换
double d;
string salary;
string s4="12.56";
//尖括号内是返回类型
d=convert<double>(s4); //d等于12.56
salary=convert<string>(9000.0); //salary等于"9000"
//以下是错误的用法
// d=convert(s4);
// salary=convert(9000.0);
cout<<d<<endl;
cout<<salary<<endl<<endl;
return 0;
}