您的位置:首页 > 编程语言 > C语言/C++

C++double转化为string

2015-06-18 22:45 330 查看

C++ 将double转化为string

cout<<(b->getDescription())<<endl;

cout<<(b->cost())<<endl;

2. #include <sstream>

ostringstream sstr;
sstr << b->cost();
cout<<(b->getDescription()+ "$ "+ sstr.str());


3. 有许多这种变换的话

// stringcast.h

#ifndef _H_STRING_CAST_

#define _H_STRING_CAST_

#include <string>

#include <sstream>

template <typename T>

std::string string_cast(const T& in)

{

static std::ostringstream stream;

stream.str("");

stream << in;

return stream.str();

}

template <typename T>

T string_cast(const std::string& in)

{

static T out;

std::istringstream s(in);

s >> out;

return out;

}

#endif

You can then just do:

std::string str = string_cast<int>(10);

EDIT. If you use boost, you can also use lexical_cast
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: