example6.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <stdexcept>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <boost/safe_numerics/safe_integer.hpp>
  5. int main(int, const char *[]){
  6. // problem: checking of externally produced value can be overlooked
  7. std::cout << "example 6: ";
  8. std::cout << "checking of externally produced value can be overlooked" << std::endl;
  9. std::cout << "Not using safe numerics" << std::endl;
  10. std::istringstream is("12317289372189 1231287389217389217893");
  11. try{
  12. int x, y;
  13. is >> x >> y; // get integer values from the user
  14. std::cout << x << ' ' << y << std::endl;
  15. std::cout << "error NOT detected!" << std::endl;
  16. }
  17. catch(const std::exception &){
  18. std::cout << "error detected!" << std::endl;
  19. }
  20. // solution: assign externally retrieved values to safe equivalents
  21. std::cout << "Using safe numerics" << std::endl;
  22. {
  23. using namespace boost::safe_numerics;
  24. safe<int> x, y;
  25. is.seekg(0);
  26. try{
  27. is >> x >> y; // get integer values from the user
  28. std::cout << x << ' ' << y << std::endl;
  29. std::cout << "error NOT detected!" << std::endl;
  30. }
  31. catch(const std::exception & e){
  32. std::cout << "error detected:" << e.what() << std::endl;
  33. }
  34. }
  35. return 0;
  36. }