fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. template < typename T > std::string to_string( const T& value )
  6. {
  7. std::ostringstream os ;
  8. os << value ;
  9. return os.str() ;
  10. }
  11.  
  12. template < typename T > T to_value( const std::string& str )
  13. {
  14. std::istringstream is(str) ;
  15. T value ;
  16. if( is >> value >> std::ws && is.eof() ) // success
  17. return value ;
  18. else // failed
  19. // report error (throw something)
  20. return T() ;
  21. }
  22.  
  23. int main()
  24. {
  25. int i = 12345 ;
  26. std::string str = to_string(i) ;
  27. int j = to_value<int>(str) ;
  28. std::cout << "i: " << i << " str: " << str << " j: " << j << '\n' ;
  29.  
  30. double d = 123.45 ;
  31. str = to_string(d) ;
  32. double e = to_value<double>(str) ;
  33. std::cout << "d: " << d << " str: " << str << " e: " << e << '\n' ;
  34. }
  35.  
Success #stdin #stdout 0s 3036KB
stdin
Standard input is empty
stdout
i: 12345 str: 12345 j: 12345
d: 123.45 str: 123.45 e: 123.45