There are two good methods of converting variables into a string, both already mentioned. They are the 'correct' answer, as far as any answer could be correct.
Method one: Use streams for complex formatting.
std::stringstream myStream;
myStream << "Meow " << number << " wuff " << myFloat << " blah blah " << otherStuff;
std::string myResult = myStream.str();
Method two: Use a standalone function for simple formatting.
std::string myResult = "blah = " << IntToString(blah);
'IntToString()' is not a pre-existing function (though there are C-style functions that do similar in the standard library, they don't give out a std::string).
You can make your own like this: (this code has to go in a header file)
#include <sstream>
template<typename Type>
std::string ConvertToString(Type value)
{
std::stringstream sstream;
sstream << value;
return sstream.str();
}
template<typename Type>
Type ConvertFromString(const std::string &str)
{
std::stringstream sstream;
sstream << str;
Type type;
sstream >> type;
return type;
}And you can use it like this:
std::string myStr = ConvertToString(myInt);
int myInt = ConvertFromString<int>(myStr);
Well, if you use:
int ParsedNumber = std::to_int(StringThatNeedsParsing);
Like SiCrane, I'm confused by this statement. Where is "std::to_int" found in the standard library? It wasn't in the old standard, and with a few quick googles I can't find it in C++11 either. Is it a non-standard extension for some compiler?