读书人

double变换为string类型

发布时间: 2013-06-26 14:29:32 作者: rapoo

double转换为string类型
貌似用ostream还是istreamdouble变换为string类型急求,同时自己查资料中,请大神帮忙
[解决办法]
#include <sstream>
using std::stringstream;
[解决办法]
可以用stringstream.
c++11里新增了 std::to_string()可以直接用 #include <string> 不过需要编译器支持。
[解决办法]
如果没有c++11支持,也可以自己写,效率可能没那么高
#include <sstream>
string to_string(double v)
{
return (std::ostringstream()<<v).str();
}
[解决办法]
int i = type_convert<int>("123");
double j = type_convert<double>("123.555");
string str = type_convert<string>(123.555);


template<class Out_Type, class In_Type>
Out_Type type_convert(const In_Type& T)
{
stringstream ss;
ss<<T;
Out_Type result;
ss>>result;
return result;
}


[解决办法]

#include <iostream>
#include <cstdlib>
using namespace std;

void main()
{
char str[128] = { 0 };
double dnum = 11.11;
sprintf_s(str, 128, "%f", dnum);
string s = str;
cout<<str<<endl;
}

读书人网 >C++

热点推荐