1 | // Boost.Convert test and usage example |
2 | // Copyright (c) 2009-2020 Vladimir Batov. |
3 | // Use, modification and distribution are subject to the Boost Software License, |
4 | // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt. |
5 | |
6 | #include "./test.hpp" |
7 | |
8 | #if !defined(BOOST_CONVERT_CXX14) |
9 | int main(int, char const* []) { return 0; } |
10 | #else |
11 | |
12 | #include <boost/convert.hpp> |
13 | #include <boost/convert/lexical_cast.hpp> |
14 | |
15 | using std::string; |
16 | using boost::convert; |
17 | |
18 | struct boost::cnv::by_default : boost::cnv::lexical_cast {}; |
19 | |
20 | static |
21 | void |
22 | test_invalid() |
23 | { |
24 | char const* str[] = { "not" , "1 2" , " 33" , "44 " , "0x11" , "7 + 5" }; |
25 | int const size = sizeof(str) / sizeof(str[0]); |
26 | |
27 | for (int k = 0; k < size; ++k) |
28 | { |
29 | boost::optional<int> const res = convert<int>(str[k]); |
30 | bool const failed = !res; |
31 | |
32 | if (!failed) |
33 | { |
34 | printf("test::cnv::invalid() failed for: <%s><%d>\n" , str[k], res.value()); |
35 | } |
36 | BOOST_TEST(failed); |
37 | } |
38 | } |
39 | |
40 | static |
41 | void |
42 | test_dbl_to_str() |
43 | { |
44 | // printf("100.00 %s\n", convert<string>( 99.999).value().c_str()); |
45 | // printf( "99.95 %s\n", convert<string>( 99.949).value().c_str()); |
46 | // printf("-99.95 %s\n", convert<string>(-99.949).value().c_str()); |
47 | // printf( "99.9 %s\n", convert<string>( 99.949).value().c_str()); |
48 | // printf( "1.00 %s\n", convert<string>( 0.999).value().c_str()); |
49 | // printf( "-1.00 %s\n", convert<string>( -0.999).value().c_str()); |
50 | // printf( "0.95 %s\n", convert<string>( 0.949).value().c_str()); |
51 | // printf( "-0.95 %s\n", convert<string>( -0.949).value().c_str()); |
52 | // printf( "1.9 %s\n", convert<string>( 1.949).value().c_str()); |
53 | // printf( "-1.9 %s\n", convert<string>( -1.949).value().c_str()); |
54 | } |
55 | |
56 | int |
57 | main(int, char const* []) |
58 | { |
59 | string const not_int_str = "not an int" ; |
60 | string const std_str = "-11" ; |
61 | char const* const c_str = "-12" ; |
62 | int const v00 = convert<int>(not_int_str).value_or(-1); |
63 | int const v01 = convert<int>( std_str).value_or(-1); |
64 | int const v02 = convert<int>( c_str).value_or(-1); |
65 | |
66 | BOOST_TEST(v00 == -1); // Failed conversion. No throw |
67 | BOOST_TEST(v01 == -11); |
68 | BOOST_TEST(v02 == -12); |
69 | |
70 | test_invalid(); |
71 | test_dbl_to_str(); |
72 | |
73 | return boost::report_errors(); |
74 | } |
75 | |
76 | #endif |
77 | |