fork download
  1. #include <sstream>
  2. #include <exception>
  3. #include <vector>
  4. #include <string>
  5. #include <iostream>
  6.  
  7.  
  8. class bad_from_string : public std::exception
  9. {
  10. public:
  11. bad_from_string(std::string const& s)
  12. : msg(s) {}
  13. const char * what() const noexcept
  14. {
  15. return msg.c_str();
  16. }
  17.  
  18. private:
  19. std::string msg;
  20. };
  21.  
  22.  
  23. template<class T>
  24. T from_string(std::string const& s)
  25. {
  26. try {
  27. std::istringstream iss(s);
  28. iss.exceptions(std::ios::failbit | std::ios::badbit);
  29. T ret;
  30. iss >> std::noskipws >> ret;
  31. return ret;
  32. }
  33. catch( std::exception & err )
  34. {
  35. throw( bad_from_string("fuck you") );
  36. }
  37. }
  38.  
  39. int main()
  40. {
  41. #define _CATCH() catch (std::exception const& e) { std::cout<<"catch std::exception: "<< e.what(); } catch (...) { std::cout<<"catch unknown"; }
  42.  
  43. std::vector<std::string> strings{ "123", "12.3", "", " ", "abc", " 123", "123 ", "12 3", "-1", "a", "A" };
  44. for (auto& str : strings)
  45. {
  46. std::cout << std::endl << "from_string(\'" << str << "\'):";
  47. try { std::cout << std::endl << "<string>: "; std::cout << from_string<std::string>(str); } _CATCH()
  48. try { std::cout << std::endl << "<double>: "; std::cout << from_string<double>(str); } _CATCH()
  49. try { std::cout << std::endl << "<int> : "; std::cout << from_string<int>(str); } _CATCH()
  50. try { std::cout << std::endl << "<char> : "; std::cout << from_string<char>(str); } _CATCH()
  51. std::cout << std::endl;
  52. }
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
from_string('123'):
<string>: 123
<double>: 123
<int>   : 123
<char>  : 1

from_string('12.3'):
<string>: 12.3
<double>: 12.3
<int>   : 12
<char>  : 1

from_string(''):
<string>: catch std::exception: fuck you
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  : catch std::exception: fuck you

from_string(' '):
<string>: catch std::exception: fuck you
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  :  

from_string('abc'):
<string>: abc
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  : a

from_string(' 123'):
<string>: catch std::exception: fuck you
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  :  

from_string('123 '):
<string>: 123
<double>: 123
<int>   : 123
<char>  : 1

from_string('12 3'):
<string>: 12
<double>: 12
<int>   : 12
<char>  : 1

from_string('-1'):
<string>: -1
<double>: -1
<int>   : -1
<char>  : -

from_string('a'):
<string>: a
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  : a

from_string('A'):
<string>: A
<double>: catch std::exception: fuck you
<int>   : catch std::exception: fuck you
<char>  : A