fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <cmath>
  4. #include <stdexcept>
  5.  
  6. double string_to_double(std::string s, unsigned short radix)
  7. {
  8. std::size_t decimal_pos = s.find('.');
  9. int decimals = 0;
  10. if(decimal_pos != std::string::npos)
  11. {
  12. s.erase(decimal_pos, 1);
  13. decimals = s.size() - decimal_pos;
  14. }
  15. size_t errpos;
  16. double answer = stoll(s, &errpos, radix) / std::pow(radix, decimals);;
  17. if(errpos < s.size())
  18. throw std::invalid_argument("parse error in string_to_double");
  19. return answer;
  20. }
  21. int main()
  22. {
  23. std::cout << string_to_double("10.A",16) << '\n'
  24. << string_to_double("1001.1",2) << '\n'
  25. << string_to_double("123.4",10) << '\n'
  26. << string_to_double("-.123",10) << '\n'
  27. << string_to_double("abc",16) << '\n'
  28. << string_to_double("111",2) << '\n';
  29.  
  30. }
  31.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
16.625
9.5
123.4
-0.123
2748
7