How to convert a string into a numeric type?


/ 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. bool from_string(T& t,
  7. const std::string& s,
  8. std::ios_base& (*f)(std::ios_base&))
  9. {
  10. std::istringstream iss(s);
  11. return !(iss >> f >> t).fail();
  12. }
  13.  
  14. int main()
  15. {
  16. int i;
  17. float f;
  18.  
  19. // the third parameter of from_string() should be
  20. // one of std::hex, std::dec or std::oct
  21. if(from_string<int>(i, std::string("ff"), std::hex))
  22. {
  23. std::cout << i << std::endl;
  24. }
  25. else
  26. {
  27. std::cout << "from_string failed" << std::endl;
  28. }
  29.  
  30. if(from_string<float>(f, std::string("123.456"), std::dec))
  31. {
  32. std::cout << f << std::endl;
  33. }
  34. else
  35. {
  36. std::cout << "from_string failed" << std::endl;
  37. }
  38. return 0;
  39. }

URL: http://www.codeguru.com/forum/showthread.php?t=231054

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.