开发者

Convert a Long in a String C++? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C++ long to string

Easiest way to convert int to string in C++

I am use to Java where I could just use .toString() on almost anything but I am trying a few prob开发者_运维技巧lems in C++

I can not figure out how to make a long value into a string.


You can either use a string stream:

#include <sstream>
#include <string>

long x;
// ...
std::ostringstream ss;
ss << x;

std::string result = ss.str();

Or you can use Boost's lexical_cast:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(x);

I think it's a common opinion that this aspect of the language isn't quite as elegant as it could be.

In the new C++11, things are a bit easier, and you can use the std::to_string() function:

#include <string>
std::string s = std::to_string(x);


#include <string>
#include <sstream>

std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();


You can use a stringstream.

std::ostringstream ss;
ss << aLongNumber;
ss.str()

You use operator << like iostream cout and cin. And you use str() method to get the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜