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); } 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); to_string works).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.
Can have this :
template <typename T> string CovertToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } NumberToString(), since this will work for any object for which such a streaming operator exists.