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
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 (eg, no temporaries involved, no dangling pointers)?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.