10

I want to cast a long to a cstring.

I've been struggling with this for a while and I've seen so many variants of solving this problem, more or less riddled with hassle and angst.

I know the question seems subjective, but it really shouldn't be in my opinion. There must be a way considered to be the best when the circumstances involve MFC and the standard libs that come with those circumstances.

I'm looking for a one-line solution that just works. Sort of like long.ToString() in C#.

Igor Milla
  • 2,767
  • 4
  • 36
  • 44
Phil
  • 3,934
  • 12
  • 38
  • 62
  • 3
    What exactly are you after? Converting the number stored in a long to a string or the 4 characters stored in a long into their respective characters? – Goz Sep 23 '11 at 15:47
  • Goz asks a very good question... and neither one would be called "casting". – Ben Voigt Sep 23 '11 at 15:56
  • 1
    *"Sort of like long.ToString() in C#."* to me says he's simply new to C++ and looking for the simple answer. – AJG85 Sep 23 '11 at 15:59
  • AJG85, you couldn't be more right. I want to print the long's value and to do that I need to convert it to a string. – Phil Sep 23 '11 at 16:06
  • Technically you could also use `System.Convert.ToString(value)` with C++/CLI but that's not the *real* C++ answer. – AJG85 Sep 23 '11 at 16:17
  • it's not a particularly good fit for your situation here (with CString), but for more general conversions between standard types, you might have a look at [boost lexical_cast](http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm). – Mike Ellery Sep 23 '11 at 18:20

2 Answers2

22

It's as simple as:

long myLong=0;
CString s;

// Your one line solution is below
s.Format("%ld",myLong);
Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
6

There are many ways to do this:

CString str("");
long l(42);

str.Format("%ld", l); // 1
char buff[3];
_ltoa_s(l, buff, 3, 10); // 2
str = buff;
str = boost::lexical_cast<std::string>(l).c_str(); // 3
std::ostringstream oss;
oss << l; // 4
str = oss.str().c_str();
// etc
AJG85
  • 15,849
  • 13
  • 42
  • 50
  • The ISO C++ conformant _ltoa should be used in preference to the deprecated ltoa function. Also, the buffer passed in as the second argument cannot be NULL, so a temp buffer will be necessary if _ltoa is used. – Michael Goldshteyn Sep 23 '11 at 16:02
  • Right, I never use any of these. Editing. – AJG85 Sep 23 '11 at 16:05