Search code examples
c++boostlexical-cast

how to convert string to unsigned short using boost lexical cast?


I have a string containing the port, when I try to create a tcp endpoint I need its value in unsigned short

  std::string to_port;
    ....
    boost::lexical_cast<unsigned short>(to_port));

throws an exception bad lexical cast: source type value could not be interpreted as target


Solution

  • The following program works correctly:

    #include <iostream>
    #include <boost/lexical_cast.hpp>
    
    int main(int argc, const char *argv[])
    {
        std::string to_port("8004");
        unsigned short intport = boost::lexical_cast<unsigned short>(to_port);
    
        std::cout << intport << std::endl;
        std::cout << std::hex << intport << std::endl;
        return 0;
    }
    

    But if we modify the first line of main into:

    std::string to_port;
    

    We get the exception:

    terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
      what():  bad lexical cast: source type value could not be interpreted as target
    Aborted (core dumped)
    

    Which leads to the conclusion that there's something wrong with the parameter you are passing to the lexical_cast.

    Can you print the to_port variable to verify its content just before the lexical_cast? Are you sure it is properly initialized and still in-scope when used (e.g., no temporaries involved, no dangling pointers)?