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