1// Copyright (c) 2018 Robert Ramey
2//
3// Distributed under the Boost Software License, Version 1.0. (See
4// accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7#include <stdexcept>
8#include <sstream>
9#include <iostream>
10
11#include <boost/safe_numerics/safe_integer.hpp>
12
13int main(int, const char *[]){
14 // problem: checking of externally produced value can be overlooked
15 std::cout << "example 6: ";
16 std::cout << "checking of externally produced value can be overlooked" << std::endl;
17 std::cout << "Not using safe numerics" << std::endl;
18
19 std::istringstream is("12317289372189 1231287389217389217893");
20
21 try{
22 int x, y;
23 is >> x >> y; // get integer values from the user
24 std::cout << x << ' ' << y << std::endl;
25 std::cout << "error NOT detected!" << std::endl;
26 }
27 catch(const std::exception &){
28 std::cout << "error detected!" << std::endl;
29 }
30
31 // solution: assign externally retrieved values to safe equivalents
32 std::cout << "Using safe numerics" << std::endl;
33 {
34 using namespace boost::safe_numerics;
35 safe<int> x, y;
36 is.seekg(0);
37 try{
38 is >> x >> y; // get integer values from the user
39 std::cout << x << ' ' << y << std::endl;
40 std::cout << "error NOT detected!" << std::endl;
41 }
42 catch(const std::exception & e){
43 std::cout << "error detected:" << e.what() << std::endl;
44 }
45 }
46 return 0;
47}
48

source code of boost/libs/safe_numerics/example/example6.cpp