1

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 problems in C++

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

Community
  • 1
  • 1
Seth Hikari
  • 2,711
  • 6
  • 27
  • 32

3 Answers3

9

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);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Added another standard solution for completeness :) Also, I noted that inline editing silently steps over other people's changes. – R. Martinho Fernandes Sep 20 '11 at 23:04
  • @RMF: Thanks for the edit, I didn't know that! Maybe the days of inelegance are over! – Kerrek SB Sep 20 '11 at 23:05
  • @Seth: Yes, that did not exist in the previous versions of the standard. Also the inverse operations like `stoi()` and `strtoull()` have overloads for `std::string` in C++11. – Kerrek SB Sep 20 '11 at 23:08
0
#include <string>
#include <sstream>

std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();
Ed S.
  • 122,712
  • 22
  • 185
  • 265
0

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.

axel22
  • 32,045
  • 9
  • 125
  • 137
carlos prado
  • 49
  • 2
  • 6