Nov
26
Casting to and from STL strings.
Here are a couple of functions to convert numbers to strings and strings to numbers. I didn't invent this technique. Boost used to do it this way a long time ago, but then they convert things over to a more complex and robust technique. I really like this old way, because it is very simple and works for most cases.
#include <sstream> #include <string> // //Template function to convert any numerical type //into a stl string. // template<typename To, typename From> std::wstring string_cast(From value) { std::wostringstream os; os << value; return os.str(); } // //Template function to convert any string that contains //a numerical value into its intrinsic value. // template<typename To> T lexical_cast(const std::wstring& str) { std::wistringstream is(str); T value; is >> value; return value; } int main() { // //Start off with any numerical value as a string // std::wstring srcStringFloat = L"23.45"; // //Cast it into the destination type. // float destFloatValue = 0.0f; destFloatValue = lexical_cast<float>(srcStringFloat); // // Now go the other way. // // // Start off with any numerical value. // float srcFloat = -0.00004F; // //Cast the value into a string. // std::wstring dstStringValue; dstStringValue = string_cast<std::wstring>(srcFloat); return 0; }