0

When running the following

    bool my_compare(const std::string& string_1, const std::string& string_2)
    {
        const boost::regex str_re("so(m)e_(r)e(g)ex");
        boost::smatch str_match;     

        size_t one;
        uint8_t two;
        size_t three;
        if( boost::regex_search(string_1, str_match, str_re) ) {
            one = boost::lexical_cast<size_t>( std::string(str_match[1].first, match[1].second) );
            two = boost::lexical_cast<uint8_t>( std::string(str_match[2].first, match[2].second) );
            three = boost::lexical_cast<size_t>( std::string(str_match[3].first, match[3].second) );
        }
        size_t four;
        uint8_t five;
        size_t six;
        if( boost::regex_search(string_1, str_match, str_re) ) {
            four = boost::lexical_cast<size_t>( std::string(str_match[1].first, match[1].second) );
            five = boost::lexical_cast<uint8_t>( std::string(str_match[2].first, match[2].second) );
            six = boost::lexical_cast<size_t>( std::string(str_match[3].first, match[3].second) );
        }
        return false;
    }

    int main()
    {
       my_compare(some_string1, some_string2);
       return 0;
    }

I'm getting the following error, which I don't understand:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl

' what(): bad lexical cast: source type value could not be interpreted as target

3
  • are str_match and match supposed to be the same? It helps to post code that compiles. Commented Mar 4, 2014 at 18:41
  • match[x] is generated by regex. str_match is the object used for the result Commented Mar 4, 2014 at 18:43
  • The code shown doesn't initialize or even declare anything called match. Commented Mar 4, 2014 at 18:46

1 Answer 1

1

"so(m)e_(r)e(g)ex"

This regex will populate capture str_match[1] with the string "m", str_match[2] with the string "r" and str_match[3] with the string "g"

 boost::lexical_cast<size_t>( std::string(str_match[1].first, match[1].second) );

This will attempt to convert the string "m" into a value of type size_t, which fails ("m" is not an integer!), and throws the exception

' what(): bad lexical cast: source type value could not be interpreted as target

(by the way, you don't need to jump these hoops with string constructor from a pair of iterators, submatches are directly convertible to strings)

Sign up to request clarification or add additional context in comments.

1 Comment

the regex was an example which is not what I'm using. However, you helped me find the problem with casting. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.