78

How do I convert a long to a string in C++?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195

12 Answers12

99

In C++11, there are actually std::to_string and std::to_wstring functions in <string>.

string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
jichi
  • 6,333
  • 1
  • 31
  • 25
61

You could use stringstream.

#include <sstream>

// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;

There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.

The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

Skurmedel
  • 21,515
  • 5
  • 53
  • 66
29

Well if you are fan of copy-paste, here it is:

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
    std::stringstream ss;
    ss << t;
    return ss.str();
}
Gordon Freeman
  • 1,117
  • 9
  • 22
  • 1
    You missed `template `. – avakar Jun 03 '09 at 22:51
  • Well it can be discussed,it is up to compiler implementation, templates are only expanded inline when the compiler deems it appropriate – Gordon Freeman Jun 03 '09 at 23:43
  • 1
    The same holds for inline functions. Surprisingly, the `inline` keyword has little to do with code inlining (at least since 1998, anyway) --- it merely marks a function so that the linker doesn't complain about multiple definitions. – avakar Jun 04 '09 at 05:15
20

boost::lexical_cast<std::string>(my_long) more here http://www.boost.org/doc/libs/1_39_0/libs/conversion/lexical_cast.htm

Piotr Findeisen
  • 19,480
  • 2
  • 52
  • 82
  • 1
    +1, although originally, lexical_cast did little more than the accepted stringstream example (just wrapped up more expressively). – philsquared Jun 03 '09 at 23:06
18

You can use std::to_string in C++11

long val = 12345;
std::string my_val = std::to_string(val);
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
13
int main()
{
    long mylong = 123456789;
    string mystring;
    stringstream mystream;
    mystream << mylong;
    mystring = mystream.str();
    cout << mystring << "\n";
    return 0;
}
dreadwail
  • 15,098
  • 21
  • 65
  • 96
10

I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.

Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..

Anyway, if your teacher is the same, here is the hard way to do it..

std::string LongToString(long value)
{
  std::string output;
  std::string sign;

  if(value < 0)
  {
    sign + "-";
    value = -value;
  }

  while(output.empty() || (value > 0))
  {
    output.push_front(value % 10 + '0')
    value /= 10;
  }

  return sign + output;
}

You could argue that using std::string is not "the hard way", but I guess what counts in the actual agorithm.

beef2k
  • 2,233
  • 2
  • 19
  • 20
5

There are several ways. Read The String Formatters of Manor Farm for an in-depth comparison.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4
   #include <sstream>


   ....

    std::stringstream ss;
    ss << a_long_int;  // or any other type
    std::string result=ss.str();   // use .str() to get a string back
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
2

Check out std::stringstream.

Don
  • 777
  • 4
  • 4
2

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

The answers so far have given you some default output, but perhaps not the right ones.

Greg Domjan
  • 13,943
  • 6
  • 43
  • 59
  • Love it, I give a considered answer to the question to help with the thinking about the homework rather than giving the answer that was already there and I get a downvote, meanwhile 'std::stringstream' has an upvote... – Greg Domjan Jun 11 '10 at 17:59
-1

The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:

char buf[5] = {0}; // one extra byte for null    
sprintf(buf, "%l", var_for_long);
rtn
  • 127,556
  • 20
  • 111
  • 121
cmaxo
  • 31
  • 4
  • 1
    -1. While a C++ compiler will compile your code, it should certainly not be called C++. Additionally, I doubt 5 characters is enough. – avakar Jun 03 '09 at 22:49
  • 1
    Please don't advocate sprintf in this day and age. Don't we have enough buffer overrun exploits? Not that this code seems to have any as written - but you never know how things change. – philsquared Jun 03 '09 at 23:09
  • 1
    Phil, the buffer will overflow for any number above 10000. – avakar Jun 03 '09 at 23:11
  • avakar - you're absolutely right :-s that'll teach me to post to SO on the way home from the pub. – philsquared Jun 04 '09 at 13:00
  • 1
    I agree that there are some dangers with the printf family but I don't think that we can run away from them. In a perfect world we could ignore them but I work in a c++ code base that uses them and it's good to know how / why they are dangerous. Anytime you approach low level system programming you will run into these calls. Admittedly my example wasn't the best but now it's documented why it was bad and others can learn from it. Internally we use asprintf and vasprintf to safeguard against buffer overruns. – cmaxo Jun 04 '09 at 16:15