c++如何在字符串中放入双精度

c++ How to put a double into a String

本文关键字:双精度 字符串 c++      更新时间:2023-10-16

在java中,使用字符串可以完成以下操作:

int stuff;
string otherstuff;
otherstuff = "I like this much stuff: " + stuff;

但在C++中,我不知道如何操作。

在C++11中:

otherstuff = "I like this much stuff: " + std::to_string(stuff);

历史上(有时在C++11中仍然有用):

std::ostringstream ss;
ss << "I like this much stuff: " << stuff;
otherstuff = ss.str();

我喜欢使用字符串流来处理这样的事情。

std::stringstream ss;
double dub = 3.14159254;
ss << dub;
std::string s = ss.str();

同样值得注意的是boost::lexical_cast<std::string>(stuff)。如果由于某种原因您不能使用C++11