Convert a Long in a String C++? [duplicate]
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.
精彩评论