Convert numeric type to String


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4.  
  5. template <class T>
  6. std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
  7. {
  8. std::ostringstream oss;
  9. oss << f << t;
  10. return oss.str();
  11. }
  12.  
  13. int main()
  14. {
  15. // the second parameter of to_string() should be one of
  16. // std::hex, std::dec or std::oct
  17. std::cout<<to_string<long>(123456, std::hex)<<std::endl;
  18. std::cout<<to_string<long>(123456, std::oct)<<std::endl;
  19. return 0;
  20. }
  21.  
  22. /* output:
  23. 1e240
  24. 361100
  25. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.