5

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

3 Answers 3

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); 
Sign up to request clarification or add additional context in comments.

5 Comments

oh that's cute +1; is that a C++11 thing?
Note: this is only supported by compilers with C++11 support (which you should probably have, by now).
@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).
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: stackoverflow.com/questions/14617950/… 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 :).
VS 2010 is not a full implementation of C++ 2011.
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.

Comments

1

Can have this :

 template <typename T> string CovertToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } 

1 Comment

I'd consider calling it something besides NumberToString(), since this will work for any object for which such a streaming operator exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.