// ostringtreamTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <sstream>
using namespace std;
template<class out_type,class in_value_type>
out_type type_convert(const in_value_type& t)
{
stringstream _sstream;
_sstream<<t;
out_type _result;
_sstream>>_result;
return _result;
}
int _tmain(int argc, _TCHAR* argv[])
{
double d_value;
string str_value="123.2";
d_value = type_convert<double>(str_value);
cout<<"d_value: "<<d_value<<endl;
return 0;
}
几种转换方式:
// ostringtreamTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <sstream>
using namespace std;
template<class out_type,class in_value_type>
out_type type_convert(const in_value_type& t)
{
stringstream _sstream;
_sstream<<t;
out_type _result;
_sstream>>_result;
return _result;
}
int _tmain(int argc, _TCHAR* argv[])
{
double d_value;
int i_value;
char str_i_value[]="20";
char str_d_value[]="20.21";
//字符串转数值
i_value = atoi(str_i_value);
d_value = atof(str_d_value);
cout<<"i_value:"<<i_value<<" | "<<"d_value:"<<d_value<<endl<<endl;
//数值转字符串
memset(str_i_value,0,sizeof(str_i_value));
memset(str_d_value,0,sizeof(str_d_value));
sprintf(str_i_value,"%d",i_value);
_gcvt(d_value,4,str_d_value);
cout<<"str_i_value:"<<str_i_value<<" | str_d_value:"<<str_d_value<<endl<<endl;
//stream 转换
i_value = 0;
d_value = 0;
d_value = type_convert<double>(str_d_value);
i_value = type_convert<int>(str_i_value);
cout<<"i_value:"<<i_value<<" | "<<"d_value:"<<d_value<<endl;
return 0;
}