fork download
  1. #include <stdexcept>
  2. #include <string>
  3. #include <sstream>
  4. #include <iostream>
  5. #include <limits>
  6.  
  7. template<class T>
  8. std::wstring ToString(T input)
  9. {
  10. std::wostringstream ss;
  11. ss.precision(std::numeric_limits<T>::digits10);
  12. ss << input;
  13. if (!ss.good())
  14. {
  15. //Raise your favorite exception.
  16. throw std::runtime_error("Invalid input.");
  17. }
  18. return std::wstring(ss.str());
  19. }
  20.  
  21. template<class T>
  22. T FromString(const wchar_t *input)
  23. {
  24. std::wistringstream ss(input);
  25. ss.precision(std::numeric_limits<T>::digits10);
  26. T output;
  27. ss >> output;
  28. if (ss.fail() || !ss.eof())
  29. {
  30. //Raise your favorite exception.
  31. throw std::runtime_error("Invalid input.");
  32. }
  33. return output;
  34. }
  35.  
  36. template<class T>
  37. T FromString(const std::wstring &input)
  38. {
  39. return FromString<T>(input.c_str());
  40. }
  41.  
  42. std::wstring operator+(const wchar_t *op1, const std::wstring &op2)
  43. {
  44. return std::wstring(op1) + op2;
  45. }
  46.  
  47. int main()
  48. {
  49. double pi = 3.14159265359;
  50. std::wcout.precision(std::numeric_limits<double>::digits10);
  51. std::wcout << L"PI is " + ToString(pi) << std::endl;
  52. const wchar_t *strPi = L"3.14159265359";
  53. double newPi = FromString<double>(strPi);
  54. std::wcout << newPi << std::endl;
  55. const wchar_t *strPi2 = L"3,14159265359";
  56. try
  57. {
  58. double newPi2 = FromString<double>(strPi2);
  59. std::wcout << newPi2 << std::endl;
  60. }
  61. catch (std::exception &ex)
  62. {
  63. std::wcout << L"Exception occurred: " << ex.what() << std::endl;
  64. }
  65. double newPi3 = FromString<double>(std::wstring(strPi));
  66. std::wcout << newPi3 << std::endl;
  67. return 0;
  68. }
  69.  
Success #stdin #stdout 0.01s 2836KB
stdin
Standard input is empty
stdout
PI is 3.14159265359
3.14159265359
Exception occurred:  Invalid input.
3.14159265359