4

I want to convert an integer to a string. I tried it this way but this didn't work

void foo()
{
    int y = 1;
    string x = static_cast<string>(y);

}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
DebareDaDauntless
  • 471
  • 2
  • 7
  • 12

3 Answers3

10

The std::to_string function should do it:

string x = std::to_string(y);

For the opposite, it's std::stoi:

int z = std::stoi(y, nullptr, 10);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • oh that's cute +1; is that a C++11 thing? – Bathsheba Sep 24 '13 at 18:44
  • 2
    Note: this is only supported by compilers with C++11 support (which you should probably have, by now). – Mohammed Hossain Sep 24 '13 at 18:44
  • @Bathsheba Yes, it's new in C++11. For older compilers, your version is the solution to use (and most likely how `to_string` works). – Some programmer dude Sep 24 '13 at 18:45
  • On MS Visual Studio 2010 C++, I get this error: error C2668: 'std::to_string' : ambiguous call to overloaded function. If I cast x to (long double), everything works ok. Actually, looks like some other folks had the same problem: http://stackoverflow.com/questions/14617950/ambiguous-call-to-overloaded-function-stdto-string Anyway, not sure this answer will work on all modern compilers. VS 2010 isn't that old. But that's C++, what can you say :). – dcp Sep 24 '13 at 18:48
  • 1
    VS **2010** is not a full implementation of C++ **2011**. – Pete Becker Sep 24 '13 at 20:06
5

No that will not work since int and std::string are not related in any class heirarchy. Therefore a static_cast will fail.

An easy way (though not necessarily the fastest way) is to write

std::stringsteam ss;
ss << y;
std::string x = ss.str();

But, if you have a C++11 compiler, Joachim Pileborg's solution is much better.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Can have this :

  template <typename T>
  string CovertToString ( T Number )
  {
     ostringstream ss;
     ss << Number;
     return ss.str();
  }
P0W
  • 46,614
  • 9
  • 72
  • 119
  • 2
    I'd consider calling it something besides `NumberToString()`, since this will work for any object for which such a streaming operator exists. – cdhowie Sep 24 '13 at 18:45