tags:

views:

2237

answers:

10

Yes, it is for homework....

Anyway - how to convert long into string?

THANK YOU! ^^

+1  A: 

Check out std::stringstream.

Don
+11  A: 

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
+2  A: 
   #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
It's std::string, not std::String.
avakar
Thank you - finger trouble.
Martin Beckett
A: 

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);

cmaxo
-1. While a C++ compiler will compile your code, it should certainly not be called C++. Additionally, I doubt 5 characters is enough.
avakar
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.
Phil Nash
Phil, the buffer will overflow for any number above 10000.
avakar
avakar - you're absolutely right :-s that'll teach me to post to SO on the way home from the pub.
Phil Nash
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
+2  A: 
int main()
{
    long mylong = 123456789;
    string mystring;
    stringstream mystream;
    mystream << mylong;
    mystring = mystream.str();
    cout << mystring << "\n";
    return 0;
}
byte
+2  A: 

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

Fred Larson
That's a good article.
Skurmedel
Yes. This is at least the third time I've linked it on SO. 8v)
Fred Larson
+3  A: 

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
You missed `template <typename T>`.
avakar
Thanks,I've update answer.
Gordon Freeman
`inline` is now redundant.
avakar
Well it can be discussed,it is up to compiler implementation, templates are only expanded inline when the compiler deems it appropriate
Gordon Freeman
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
+2  A: 

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
This time it's fine to use ready functions. But thanks for this neat idea.
Arnis L.
Really? He's just checking if you can _find_ a function somewhere? Yeah, times have changed ;) ..
beef2k
@beef2k Even better - he notices that i know OOP, feels impressed and doesn't check anything else. :)
Arnis L.
finding a function to use is hardly knowing oop..
Blindy
+8  A: 

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
+1, although originally, lexical_cast did little more than the accepted stringstream example (just wrapped up more expressively).
Phil Nash
A: 

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
If I needed that, i would edit my question. :)
Arnis L.
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